您的位置:首页 > 其它

leetcode || 88、Merge Sorted Array

2015-04-14 19:59 483 查看
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.

Hide Tags
Array Two
Pointers

题意:原址合并两个已序数组

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--];
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: