[LeetCode]Merge Sorted Array
2013-10-27 22:57
190 查看
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 to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
给定两个有序数组A和B,将B中的元素插入A(假设A有足够大的空间),保持有序性
Tip: A和B的大小已知,即合并完成后的数组大小确定。
将指针指向A和B的尾端,从数组的尾端(最大值)处开始合并。若B中仍有剩余元素,全部插入A的头部。
代码
class Solution { public: void merge(int A[], int m, int B[], int n) { // Note: The Solution object is instantiated only once and is reused by each test case. if(B==NULL || n==0) return; int p=m-1, q=n-1, cur=m+n-1; while(p>=0 && q>=0) { if(A[p]>=B[q]) { A[cur--] = A[p--]; } else { A[cur--] = B[q--]; } } while(q>=0) A[cur--] = B[q--]; } };
相关文章推荐
- [leetcode]Merge Sorted Array
- LeetCode Merge Sorted Array
- Merge Sorted Array [LeetCode]
- [LeetCode]88 Merge Sorted Array
- [leetcode]Merge Sorted Array @ Python
- [Leetcode][python]Merge Sorted Array
- Leetcode Merge Sorted Array
- leetcode 88 Merge Sorted Array
- [LeetCode]题解(python):088-Merge Sorted Array
- 【Leetcode】Merge Sorted Array
- LeetCode - Merge Sorted Array
- leetcode88~Merge Sorted Array
- 【LeetCode刷题记录】Merge Sorted Array
- LeetCode题解:Merge Sorted Array
- LeetCode – Merge Sorted Array (Java)
- leetcode Merge Sorted Array
- LeetCode(88)Merge Sorted Array
- LeetCode - Merge Sorted Array
- [LeetCode] Merge Sorted Array
- leetcode: Merge Sorted Array