Leetcode part of the problem solution (3)

1.合并两个有序数组  
/*
执行用时:1 ms, 在所有 Java 提交中击败了24.22%的用户
内存消耗:40.1 MB, 在所有 Java 提交中击败了5.06%的用户
*/
class Solution {
    
    
    public void merge(int[] nums1, int m, int[] nums2, int n) {
    
    
        int i=0 ;
        int j = 0;
        //n为0时,不对nums1进行操作。
        if(n!=0){
    
    
           while(j<n&&i<m+j){
    
    
               //当nums[j]<=num1[i]时,将nums[i]及后面元素后移一位。
                if (nums2[j]<=nums1[i]){
    
    
                    int temp ;
                    for (temp=m+j;temp>i;temp--){
    
    
                        nums1[temp]=nums1[temp-1];
                    }
                    nums1[i]=nums2[j];
                    j++;
                }
                i++;
            }
        //当j<n时,把nums2[j]后面的元素赋值给nums1
          if (j<n){
    
    
              System.arraycopy(nums2, j, nums1, m+j, n-j);
          }
        }
    }
}



/*
官方解答,最为致命!
执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗:39.6 MB, 在所有 Java 提交中击败了5.06%的用户
*/
class Solution {
    
    
    public void merge(int[] nums1, int m, int[] nums2, int n) {
    
    
        //利用指针从后往前走
        int p1 = m-1;
        int p2 = n-1;
        int p = m+n-1;
        //谁大谁赋值给num[p],并自己往前走一位
        while(p1>=0&&p2>=0){
    
    
            nums1[p--] = nums1[p1]>nums2[p2]?nums1[p1--]:nums2[p2--];
        }
        System.arraycopy(nums2, 0, nums1, 0, p2+1);

    }
}

2.买卖股票的最佳时机  
/*
执行用时:356 ms, 在所有 Java 提交中击败了7.33%的用户
内存消耗:40 MB, 在所有 Java 提交中击败了5.32%的用户
*/
class Solution {
    
    
    public int maxProfit(int[] prices) {
    
    
        int max = 0;
        int min = 999;
        int num = 0;
        int i,j;
        if (prices.length==0){
    
    
            return 0;
        }
        for (i=0;i<prices.length;i++){
    
    
                max = prices[i];
                for (j=0;j<i;j++){
    
    
                        min = prices[j];
                        if(max-min>num)
                        num = max - min;
                }
        }
        return num;
    }
}
3.二进制进位
/*
利用carry来保存进位
*/
class Solution {
    
    
    public String addBinary(String a, String b) {
    
    
        int longer = a.length();
        int shorter = b.length();
        if (shorter>longer) return addBinary(b, a);
        int l = Math.max(longer, shorter);
        int i, j=shorter-1 ;
        int carry = 0;
        StringBuilder stringBuilder = new StringBuilder();
        for (i = l-1;i>=0;i--){
    
    
            if(a.charAt(i)=='1') carry++;
            if (j>=0&&b.charAt(j--)=='1') carry++;
            if (carry%2==1) stringBuilder.append('1');
            else stringBuilder.append('0');
            carry/=2;
        }
        if (carry==1) stringBuilder.append('1');
        stringBuilder.reverse();
        return stringBuilder.toString(); 

    }
}

Let’s post these 3 first, and then I’m going to swipe the data structure card.

Guess you like

Origin blog.csdn.net/qq_41458842/article/details/106890003