兩個升序數組合併成一個有序數組

題:兩個升序數組合併成一個升序數組。

  • 利用題中數組是生序排列的。代碼如下:代碼中去除了相同元素
@Test
    public void test() {
        // 定義兩個數組 a ,b  生序排列
        int[] a = {1, 3, 11, 34, 444, 555, 9999};
        int[] b = {20, 22, 55, 800, 10000, 22222};
        // 定義新的存儲空間
        List<Integer> resultList = new ArrayList<Integer>();
        // 利用數組本身就是生序排列的 ,只需要比較每個數組最小的值,將小的加入新的空間,然後小的角標+1,依次循環。
        int i = 0;
        int j = 0;
        while (i < a.length && j < b.length) {
            if (a[i] < b[j]) {
                // 小的添加到新開闢的空間 然後 i++
                resultList.add(a[i++]);
            } else if (a[i] > b[j]) {
                // 小的添加到新開闢的空間 然後 j++
                resultList.add(b[j++]);
            } else {
                // 如果相同添加進去一個
                resultList.add(a[i]);
                i++;
                j++;
            }
        }
        // 因爲原數組是生序排列,如果兩個數組長度不同那麼必定會有一個數組沒有添加完
        while (i < a.length) {
            resultList.add(a[i++]);
        }
        while (j < b.length) {
            resultList.add(b[j++]);
        }
        System.out.println(resultList);
    }

最終結果如下:

[1, 3, 11, 20, 22, 34, 55, 444, 555, 800, 9999, 10000, 22222]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章