数组合并

来源:互联网 发布:php static 编辑:程序博客网 时间:2024/05/25 08:15

非常基本的问题,但是在循环判断里面,想的特别复杂,边界条件设置不全面,考虑输入的边界值没有完整。


记录一下思路:


首先考虑两个已排序数组合并,记录两个总长,从数组1的尾部开始依次比对合并。



  • Total Accepted: 117965
  • Total Submissions: 382909
  • Difficulty: Easy

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


void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {int len = m + n - 1;int i = m - 1;int j = n - 1;while (len >= 0){if (i >= 0 && j >= 0){nums1[len--] = nums1[i]>nums2[j] ? nums1[i--] : nums2[j--];}else if (i >= 0 && j<0){nums1[len--] = nums1[i--];}else if (i<0 && j >= 0){nums1[len--] = nums2[j--];}}}



1 0