Article Directory
THE
problem
solution
Code
思路: 对于数组问题因为有序会牵扯到挤压后面数的问题,这里合并要从末尾开始,其实如果从左边开始复杂度比较高。也不是不行。
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int i = m, j = n;
int end = m+n;
while(i>0&&j>0){
if(nums1[i-1]<=nums2[j-1]){
nums1[end-1] = nums2[j-1];
j--;
end--;
}
else {
nums1[end-1] = nums1[i-1];
i--;
end--;
}
}
while(j>0){
nums1[end-1] = nums2[j-1];
j--;
end--;
}
}
};
Summary and reflection
- When encountering an ordered array, consider starting from the end.