标签:
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
标签:
原文地址:http://www.cnblogs.com/csudanli/p/5877259.html