LeetCode--No.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.

Subscribe to see which companies asked this question

提交了不知道多少次。。。好愚蠢。。。

public class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int first = m-1;
        int second = n-1;
        if (m == 0){
            for(int i = 0; i < nums2.length; i++)
                nums1[i] = nums2[i];
            return;
        }
        if (n == 0)
            return;
        int i = m+n-1;
        while(first >= 0 && second >= 0){
            if (nums1[first] >= nums2[second]){
                nums1[i--] = nums1[first];
                first--;
            }
            else{
                nums1[i--] = nums2[second];
                second--;
            }
        }
        if (second > first){
            for(i = 0; i < second+1; i++)
                nums1[i] = nums2[i];
        }
        return;
    }
}

代碼可以改的更好看一點點!

public class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int i = m-1;
        int j = n-1;
        int k = m+n-1;
        if (m == 0){
            while(j >= 0){
                nums1[j] = nums2[j];
                j--;
            }
        }
        while(i>=0 && j >= 0){
            if(nums1[i] > nums2[j])
                nums1[k--] = nums1[i--];
            else
                nums1[k--] = nums2[j--];
        }
        while(j>=0){
            nums1[k--] = nums2[j--];
        }
        return;
    }
}


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