# leetcode 88 Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 intonums1 as one sorted array.

Note:
You may assume that nums1 has enough space (size that is greater or equal tom + n) to hold additional elements from nums2. The number of elements initialized innums1 and nums2 are m and n respectively.

Runtime Error Message:
Last executed input:
Input: [1,2,3,0,0,0], 3, [2,5,6], 3
Output: [1,2,3,5,6]
Expected: [1,2,2,3,5,6]

class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n)
{
set<int> result;
for(int i = 0;i<m;i++)
{
result.insert(nums1[i]);
}
for(int i = 0;i<n;i++)
{
result.insert(nums2[i]);
}
nums1.clear();
set<int>::iterator iter = result.begin();
for(;iter!=result.end();iter++)
{
nums1.push_back(*iter);
}
}
};

class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n)
{
multiset<int> result;
for(int i = 0;i<m;i++)
{
result.insert(nums1[i]);
}
for(int i = 0;i<n;i++)
{
result.insert(nums2[i]);
}
nums1.clear();
set<int>::iterator iter = result.begin();
for(;iter!=result.end();iter++)
{
nums1.push_back(*iter);
}
}
};

简短的解决方案：

class Solution {
public:
void merge(int A[], int m, int B[], int n) {
int k = m + n;
while (k-- > 0)
A[k] = (n == 0 || (m > 0 && A[m-1] > B[n-1])) ?  A[--m] : B[--n];
}
};


class Solution {
public:
void merge(int A[], int m, int B[], int n) {
int i=m-1;
int j=n-1;
int k = m+n-1;
while(i >=0 && j>=0)
{
if(A[i] > B[j])
A[k--] = A[i--];
else
A[k--] = B[j--];
}
while(j>=0)
A[k--] = B[j--];
}
};


python解决方案：

class Solution:
# @param A  a list of integers
# @param m  an integer, length of A
# @param B  a list of integers
# @param n  an integer, length of B
# @return nothing(void)
def merge(self, A, m, B, n):
x=A[0:m]
y=B[0:n]
x.extend(y)
x.sort()
A[0:m+n]=x


python解决方案2：thats why we love python

def merge(self, A, m, B, n):
A[m:] = B[:n]
A.sort()


|
9月前
Leetcode 4. Median of Two Sorted Arrays

21 0
|
9月前
Leetcode Find Minimum in Rotated Sorted Array 题解

33 0
Search in Rotated Sorted Array - 循环有序数组查找问题
Search in Rotated Sorted Array - 循环有序数组查找问题
58 0
LeetCode 167 Two Sum II - Input array is sorted（输入已排序数组，求其中两个数的和等于给定的数）

74 0
|

LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
112 0
|

LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
114 0
|
3月前
|
Python

43 3
|
3月前
|
JavaScript 前端开发

66 0
|
3月前
|

89 0
|
1月前
|

Array数组reduce方法与数组累加、去重
【7月更文挑战第12天】
15 1