算法题【力扣-简单】

回文数

给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数

 public boolean isPalindrome(int x) {
        //如果x小于0,直接返回false
        if(x<0)return false;
        //temp存放x原值
        int y=0,i=0,temp=x;
        while(x>0){
            int g=x%10;
            y=10*y+x%10;
            i++;
            x/=10;
        }
        //如果y等于原x值,返回true
        if(temp==y)return true;
        return false;
    }

罗马数字转整数

private static int romanToInt(String s) {
        int num = 0;
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == 'I') {
                // I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。
                if (i + 1 < chars.length && (chars[i + 1] == 'V' || chars[i + 1] == 'X')) num -= 1;
                else num += 1;
            } else if (chars[i] == 'V') num += 5;
            else if (chars[i] == 'X') {
                //X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。 
                if (i + 1 < chars.length && (chars[i + 1] == 'L' || chars[i + 1] == 'C')) num -= 10;
                else num += 10;
            } else if (chars[i] == 'L') num += 50;
            else if (chars[i] == 'C') {
                //C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。
                if (i + 1 < chars.length && (chars[i + 1] == 'D' || chars[i + 1] == 'M')) num -= 100;
                else num += 100;
            } else if (chars[i] == 'D') num += 500;
            else if (chars[i] == 'M') num += 1000;
        }
        return num;
    }

最长公共前缀

public static String longestCommonPrefix(String[] strs) {
        //如果字符串的长度为空或者0,返回""
        if(strs==null||strs.length==0)return "";
        //如果只有一个字符串,返回数组第一个字符串
        if(strs.length==1)return strs[0];
        for (int i = 1; i < strs.length; i++) {
            //得到第一个字符串与后面字符串最长公共前缀,并且覆盖第一个
            strs[0]=getTwoStrCom(strs[0],strs[i]);
        }
        return strs[0];
    }
    //比较两个字符串最长公共前缀
    public static String getTwoStrCom(String str1, String str2) {
        if (str2 == null || str1 == null || str2 == "" || str1 == "") return "";
        int len = str1.length() > str2.length() ? str2.length() : str1.length();
        StringBuffer buffer=new StringBuffer(new String(""));
        for (int i = 0; i < len; i++) {
            if(str1.charAt(i)==str2.charAt(i)){
                buffer.append(str1.charAt(i));
            }else //遇到不同的直接退出循环
                break;
        }
        return buffer.toString();
    }

有效的括号

2023-09-14

class Solution {
    public boolean isValid(String s) {
        int len=s.length();
         if(len%2!=0)return false;
         Stack<Character> stack=new Stack<>();
         for(int i=0;i<len;i++){
             char c=s.charAt(i);
             if(c=='('||c=='{'||c=='[')stack.push(c);//如果是左括号先进去,直接放进栈
             else if(stack.isEmpty())
             return false;
             //为右括号的时候需要弹出一个左括号,如果有 弹出一对括号剩下的都是对的
             else if(c==')'&&stack.pop()!='(')
             return false;
              else if(c=='}'&&stack.pop()!='{')
             return false;
              else if(c==']'&&stack.pop()!='[')
             return false;
         }
        return stack.isEmpty();//全部弹空,说明配对正确
    }
}

合并两个有序链表

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    //迭代
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if(list1==null)return list2;
        else if(list2==null)return list1;
        else if(list1.val<list2.val){
            //合并去掉头节点的链表和值较大的
            list1.next=mergeTwoLists(list1.next,list2);
            return list1;
        }
        else{
            list2.next=mergeTwoLists(list1,list2.next);
            return list2;
        }
    }
   
}

更简单的方法是,创建一个新的listnode,然后比较大小合并两个链表

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    //升序合并两个链表
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
      ListNode compareList=new ListNode();
      ListNode l=compareList;
      while(list1!=null&&list2!=null){
          if(list1.val<=list2.val){
              l.next=list1;
              list1=list1.next;
          }else{
              l.next=list2;
              list2=list2.next;
          }
          l=l.next;
      }
      l.next=list1==null?list2:list1;
      return compareList.next;
    }
}

合并两个有序数组

先合并,再排序

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int len=nums1.length;
        for(int i=0;i<n;i++){
            nums1[m+i]=nums2[i];
        }
        for(int i=0;i<len-1;i++){
            for(int j=i+1;j<len;j++){
                if(nums1[i]>=nums1[j]){
                    int temp=nums1[i];
                    nums1[i]=nums1[j];
                    nums1[j]=temp;
                }
            }
        }
        System.out.println(nums1);
    }
}

原地移除元素

class Solution {
    public int removeElement(int[] nums, int val) {
        int len=nums.length;
        int n=0;
        Stack<Integer> stack=new Stack<Integer>();
        for(int num:nums){
            if(num!=val){
                stack.push(num);
                n++;
            }
        }
        for(int i=stack.size()-1;i>=0;i--){
            nums[i]=stack.pop();
        }
        return n;
    }
}

删除有序数组中的重复项

利用hashset的去重

class Solution {
    public int removeDuplicates(int[] nums) {
        int len=nums.length;
        HashSet<Integer> hashset=new HashSet<>();//去重
        for(int num:nums){
            hashset.add(num);
        }
        Set<Integer> treeSet=new TreeSet<>();//排序
        treeSet.addAll(hashset);
        Iterator<Integer> it = treeSet.iterator();
        int i = 0;
        while (it.hasNext()) {
            nums[i] = it.next();
            i++;
        }
        return treeSet.size();
    }
}

用纯数组

class Solution {
    public int removeDuplicates(int[] nums) {
        int len=nums.length;
        //从第二个开始比较
        int n=0;
        for(int i=1;i<len;i++){
            //找到不同就开始赋值
            if(nums[i]!=nums[n]){
                nums[++n]=nums[i];
            }
        }
        return n+1;//返回索引+1为长度
    }
}

删除有序数组中的重复项,保留k位相同

class Solution {
    public int removeDuplicates(int[] nums) {
        return save(nums,2);
    }
    //数组保留k个相同数
    int save(int[] nums,int k){
        int u=0;
        for(int num:nums){
            if(u<k||nums[u-k]!=num)nums[u++]=num;//相同的时候u没有变化
        }
        return u;
    }
}

继续。。。

posted @ 2023-09-15 11:33  Liku007  阅读(42)  评论(0编辑  收藏  举报