首页 > 代码库 > LeetCode 88. Merge Sorted Array
LeetCode 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.
我们数据结构书上在讲归并排序时,是将数组插入到新的数组中,这个是插到原来的数组中,我们只需要将第二个数组的元素一个一个插进来就好
class Solution {public: void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { nums1.resize(m + n); int nums1_postion = 0, nums2_postion = 0, count_nums2 = 0; for (;nums1_postion<m + n&&nums2_postion < n;++nums1_postion) { if (nums1_postion >= m + count_nums2 || (nums1[nums1_postion] > nums2[nums2_postion])) { ++count_nums2; int temp = m+count_nums2-1; for (;temp > nums1_postion;--temp) { nums1[temp] = nums1[temp - 1]; } nums1[nums1_postion] = nums2[nums2_postion++]; } } }};
LeetCode 88. Merge Sorted Array
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。