Friday, September 27, 2013

Merge Sorted Array

Q:
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 to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.

A:

---------------------3rd pass ---------C++ ----------buggy   ?????????????????????----------
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int i = m-1, j=n-1;
while(i>=0 || j >=0){
if(i<0 || ( nums1[i] <= nums2[j] )){
nums1[i+j+1] = nums2[j];
j--;
}else{
nums1[i+j+1] = nums1[i];
i--;
}
}
}
};












---------少了一个(j>=0 的检查-----------
因此不如2nd pass的理论更清晰。 同时还利用了 nums2已经遍历完,就不需要再遍历nums1了的特性



-----------------------2nd pass --------- C++ ------------------

public class Solution { 
    public void merge(int A[], int m, int B[], int n) {
        int iA = m-1,iB=n-1;
        while(iB>=0){
            if(iA>=0 && A[iA] > B[iB]){
                A[iA+iB+1] = A[iA];
                iA--;
            }else{
                A[iA+iB+1] = B[iB];
                iB--;
            }
        }
    }
}

-------------------1st pass-------------- Java --------------

public class Solution {
    public void merge(int A[], int m, int B[], int n) {
        int pA = m-1;
        int pB = n-1;
        while( pB >= 0 && pA>=0){
            if(A[pA] >= B[pB] ){
                A[pA+pB+1] = A[pA];
                pA--;
            }else{
                A[pA+pB+1] = B[pB];
                pB--;
            }
        }
        // test if pA <0, then we copy the rest of B
        if(pB>=0){
            for(int i =pB;i>=0;i--){
                A[i]=B[i];
            }
        }
        
    }
}

No comments:

Post a Comment