leetcode Merge Sorted Array

Merge Sorted Array

My Submissions
Total Accepted: 67179 Total Submissions: 231573 Difficulty: Easy

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 nums1and nums2 are m and n respectively.

Show Tags
Show Similar Problems





該題不過就是兩個指針分別往後遍歷,但是在此題中採用的方法是把第二個串中的數字插入到第一個,這就導致第一個後面可能有0這種空間,最後刪除了就好。

// test88MergeSortedArray.cpp : 定義控制檯應用程序的入口點。

//


#include "stdafx.h"
#include "vector"


using std::vector;
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n);


int _tmain(int argc, _TCHAR* argv[])
{
vector<int> a = {1,0};
vector<int> b = {2};
merge(a, 1, b, 1);
return 0;
}
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) 
{
if (n == 0)
return;
else if (m == 0)
{
for (auto i = 0; i < n;i++)
{
nums1[i] = nums2[i];
// nums1.insert(nums1.begin() + i, nums2[i]);
}
return;
}
auto j = 0;
auto k = 0;
int addnum = 0;
while (j < (m + addnum) && k<n)
{
if (nums1[j] < nums2[k])
{
j++;
continue;
}
else
{
nums1.insert(nums1.begin() + j, nums2[k]);
addnum++;
k++;
j++;
}
}
if (k < n)
{
while (k < n)
{
nums1.insert(nums1.begin() + j, nums2[k]);
k++;
j++;
}
}
while (nums1.size() > m + n)  //特別注意此處,原題中
{
auto num = nums1.end();
nums1.erase(num-1);
}
}
發佈了49 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章