2015年4月15日星期三

Merge Sorted Array leetcode

Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are mand n respectively.
用倒序的方法从大到小排列,i = m+n-1 注意for循环内都是if语句 时间O(m+n)

public class Solution {
    public void merge(int A[], int m, int B[], int n) {
        int j = m - 1;
        int k = n - 1;
        for (int i = m + n - 1; i >= 0; i--){
            if (k >= 0 && j >= 0){
                if (A[j] > B[k]){
                    A[i] = A[j];
                    j--;
                } else {
                    A[i] = B[k];
                    k--;
                }
            } else if (k >= 0){
                A[i] = B[k];
                k--;
            } else {// 这个else判定可以没有 因为此时i==j
                A[i] = A[j];
                j--;
            }
        }
        
    }
}
public class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int index = m + n - 1;
        int i = m - 1;
        int j = n -1;
        while (i >= 0 && j >= 0) {
            if (nums1[i] > nums2[j]) {
                nums1[index] = nums1[i];
                i--;
                index--;
            } else {
                nums1[index] = nums2[j];
                j--;
                index--;
            }
        }
        while (j >= 0) {
            nums1[index] = nums2[j];
            j--;
            index--;
        }
    }
}

没有评论:

发表评论