标签:leetcode
链接:https://leetcode.com/problems/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.
Hide Tags Array Two Pointers
Hide Similar Problems (E) Merge Two Sorted Lists
归并两个数组,要注意的是输入中m和n两个数字指定了两个数组中的前m个数字和n个数字有效。这一题也可以用二分法排序。
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
while(nums1.size()>m)
nums1.pop_back();
while(nums2.size()>n)
nums2.pop_back();
nums1.insert(nums1.begin(),nums2.begin(),nums2.end());
sort(nums1.begin(),nums1.end());
}
};
也可以用归并排序。
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
while(nums1.size()>m)
nums1.pop_back();
while(nums2.size()>n)
nums2.pop_back();
vector<int>::iterator it1=nums1.begin();
vector<int>::iterator it2=nums2.begin();
while(it1!=nums1.end()&&it2!=nums2.end())
if(*it1>=*it2)
nums1.insert(it1,*it2++);
else
it1++;
while(it2!=nums2.end())
nums1.push_back(*it2++);
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:leetcode
原文地址:http://blog.csdn.net/efergrehbtrj/article/details/46885577