玩命加载中 . . .

88-合并两个有序数组


LeetCode 88. Merge Sorted Array

LeetCode-88
You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.

Merge nums1 and nums2 into a single array sorted in non-decreasing order.

Example 1:

Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]

method

p1指向数组1的末尾,p2指向数组2的末尾,cnt指向合并后数组的末尾

  • nums1用完了,用nums2
  • nums2用完了,用nums1
  • 都还有,看那个大就用哪个

就不用完了之后再判断哪个还有了

void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
    int p1 = m - 1;
    int p2 = n - 1;
    int cnt = m + n - 1;
    while (cnt >= 0) {
        if (p1 < 0) nums1[cnt] = nums2[p2--];
        else if (p2 < 0) nums1[cnt] = nums1[p1--];
        else if (nums1[p1] > nums2[p2]) nums1[cnt] = nums1[p1--];
        else nums1[cnt] = nums2[p2--];
        cnt--;
    }
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录