problem:
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are mand n respectively.
thinking:
(1)先合并再排序,O(m+n)lo(m+n)
(2)从后往前比较插入,不用移动元素,O(m+n)
code:
合并排序
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
for(int i=0;i<n;i++)
A[m+i]=B[i];
sort(A,A+m+n);
}
};从后往前比较插入
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int index = m + n - 1;
int aIndex = m - 1;
int bIndex = n - 1;
while(0 <= aIndex && 0 <= bIndex)
{
if (B[bIndex] > A[aIndex])
{
A[index--] = B[bIndex--];
}
else
{
A[index--] = A[aIndex--];
}
}
while(0 <= aIndex)
{
A[index--] = A[aIndex--];
}
while(0 <= bIndex)
{
A[index--] = B[bIndex--];
}
}
};
leetcode || 88、Merge Sorted Array
原文:http://blog.csdn.net/hustyangju/article/details/45046781