Leetcode_88_Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.

題目大意:
有兩個有序的數組,數組1,數組2。要求把兩個數組進行合併到數組一種。要求數組有序。假設數組1 的大小足夠大。
思路:
1.聲明一個新的數組tmp[]。
2.數組1中設置一個指針i。數組2設置一個指針j。i,j都指向數組的頭,從前往後走。如果num1[i]

    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int []tmp=new int[m+n];
        int i=0;
        int j=0;
        int index=0;
        while (i<m && j<n){
            if(nums1[i]<nums2[j]){
                tmp[index++]=nums1[i];
                i++;
            }else {
                tmp[index++]=nums2[j];
                j++;
            }
        }

        while (i<m){ //如果第一個數組有東西
            tmp[index++]=nums1[i++];
        }
        while (j<n){//如果第二個數組有東西。
            tmp[index++]=nums2[j++];
        }
        //把tmp數組弄到num1中
        for(int k=0;k<tmp.length;k++){
            nums1[k]=tmp[k];
        }
    }

分析,空間換時間時間複雜度爲O(n),空間複雜度爲O(n)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章