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.

 

nums1已经是m+n长度了,不用新申请空间。

从后向前复制。

 

 

class Solution {
public:

    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        int i = m+n-1;
        int a1 = m-1;
        int a2 = n -1;
        while(a1>=0 && a2>=0) {
            nums1[i--]= nums1[a1]>=nums2[a2] ?nums1[a1--]:nums2[a2--];
        }
        while(a1>=0) {.  没啥用
            nums1[i--] = nums1[a1--];
        }   
        while(a2>=0) {
            nums1[i--] = nums2[a2--];
        }
    }
};

 

 

 

 

 1 class Solution:
 2     def merge(self, l1, m, l2, n):
 3         """
 4         :type nums1: List[int]
 5         :type m: int
 6         :type nums2: List[int]
 7         :type n: int
 8         :rtype: void Do not return anything, modify nums1 in-place instead.
 9         """
10         i = m - 1
11         j = n - 1
12 
13         end = m+n-1
14         while(i >= 0 and j >= 0):
15             if(l1[i] > l2[j]):
16                 l1[end] = l1[i]
17                 i-=1
18             else:
19                 l1[end] = l2[j]
20                 j -= 1
21             end -=1
22 
23         while (j>=0):
24             l1[end] = l2[j]
25             j -= 1
26             end-=1

 

posted @ 2018-03-28 11:31  乐乐章  阅读(193)  评论(0编辑  收藏  举报