how to merge two sorted integer array in place using O(n) time and O(1) space cost

前端 未结 6 649
我在风中等你
我在风中等你 2020-12-01 04:38

For example, given an integer array and its two consecutive sequence \'s beginning position which are \'b1\' and \'b2\', furthermore provided with the position \'last\' whic

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-01 04:52

    I had an interview (with a very important company) a couple of hours ago and I was asked that. There is the answer in Java

    public static void main(String[] args) {
        int A[] = { 1, 3, 5, 6, 9 };
        int B[] = new int[12];
        B[0] = 3;
        B[1] = 6;
        B[2] = 8;
        B[3] = 10;
        B[4] = 11;
        B[5] = 13;
        B[6] = 15;
        mergeInB(A, B, 7);
        for (int n : B)
            System.out.print(n + " ");
    }
    
    
    
     /**
     * @param a
     * @param b - it will be modified
     * @param j = length of b
     */
    public static void mergeInB(int[] a, int[] b, int j) {
        int i = a.length - 1, k;
        j --;
        for (k = b.length-1; k >= 0; k--) {
             if (i >= 0 && j >= 0) {
                 if (a[i] > b[j]) {
                     b[k] = a[i];
                     i --;
                 }
                 else 
                  {
                     b[k] = b[j];
                     j --;
                 }               
             }
             else break;
        }
    
        while(i>=0 && k >=0) {
             b[k] = a[i];
             k --;
             i --;
        }
    
        while(j>= 0 && k >=0) {
             b[k] = b[j];
             j--;
             k--;
         }
    }
    

提交回复
热议问题