88. Merge Sorted Array

xiaoxiao2021-02-28  24

题目:

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,索引nums2,索引nums1+nums2,通过同时遍历nums1及nums2,然后将较大值添加到nums1末尾,本题需要注意的地方是,nums1为空的情况(注意:本题leetcode testcase错误,与题意不符

代码:

class Solution { public: void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { if(m==0) for(int j =0;j<n;j++) nums1[j] = nums2[j]; int idx1 = m-1; int idx2 = n-1; int len = m+n-1; while(idx1>=0 && idx2>=0) { if(nums1[idx1]>nums2[idx2]) { nums1[len--] = nums2[idx1--]; } else { nums1[len--] = nums2[idx2--]; } } while(idx2>=0) { nums1[len--] = nums2[idx2--]; } } };

转载请注明原文地址: https://www.6miu.com/read-250427.html

最新回复(0)