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

前端 未结 6 651
我在风中等你
我在风中等你 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 05:11

    Though it is not possible entirely in O(n) time, I have a proposition to do it faster than O(n^2). I use only O(1) space which is temp in my code. I am sure it should run better than O(n^2).

    private static int[] mergeSortedArrays(int[] a1, int[] a2) {
            int i = 0, j = 0;
            while (a1[i] != Integer.MIN_VALUE) {
                if (a1[i] > a2[j]) {
                    int temp = a1[i];
                    a1[i] = a2[j];
                    a2[j] = temp;
    
                    for (int k = 1; k < a2.length; k++) {
                        if (a2[k - 1] > a2[k]) {
                            temp = a2[k - 1];
                            a2[k - 1] = a2[k];
                            a2[k] = temp;
                        }
                    }
                }
                i++;
            }
            while(j < a2.length){
                a1[i++] = a2[j++];
            }
            return a1;
        }
    

提交回复
热议问题