解法:很普通的三步走法,要主要加极端条件的判断;时间会大大缩短!!!
不加判断,只能打败4.4%;
加了之后 91%
class Solution {
public:
/**
* @param A: sorted integer array A
* @param B: sorted integer array B
* @return: A new sorted integer array
*/
vector<int> mergeSortedArray(vector<int> &A, vector<int> &B) {
// write your code here
vector<int> result;
if(A.empty()) return B;
if(B.empty()) return A;
int m = A.size(), i = 0;
int n = B.size(), j = 0;
while(i < m && j < n){
if(A[i] <= B[j]){
result.push_back(A[i++]);
}
else{
result.push_back(B[j++]);
}
}
if(i < m){
while(i < m){
result.push_back(A[i++]);
}
}
else{
while(j < n){
result.push_back(B[j++]);
}
}
return result;
}
};
!!!解法er: 优化,当A很长,B很短的时候,可以用二分法,将B中的元素插入到A中。
class Solution {
public:
/**
* @param A: sorted integer array A
* @param B: sorted integer array B
* @return: A new sorted integer array
*/
vector<int> mergeSortedArray(vector<int> &A, vector<int> &B) {
// write your code here
vector<int> result;
int m = A.size();
int n = B.size();
int pa = 0;
for(int i = 0; i < n; i++){
int index = binarySearch(A,B[i]);
cout<<index<<endl;
while(pa < index){
result.push_back(A[pa++]);
}
result.push_back(B[i]);
}
while(pa < m){
result.push_back(A[pa++]);
}
return result;
}
private:
int binarySearch(vector<int> nums, int target) {
int left = 0;
int right = nums.size() - 1;
while(left <= right){
int middle = (left + right) / 2;
if(nums[middle] == target) return middle;
if(nums[middle] > target){
right = middle - 1;
}
else{
left = middle + 1;
}
}
return left;
}
};