LeetCode 88. Merge Sorted Array
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode-88 Merge Sorted Array
LeetCode 88. Merge Sorted Array
leetcode?python 88. Merge Sorted Array