题目:
给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。
思路:
为了实现O(1)的空间复杂度,从两个数组的最后开始遍历到头。这样,前面的元素就不会被覆盖
代码:
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int index1 = m-1, index2 = n-1;
int mergeIndex = m + n - 1;
while ( index1 >= 0 || index2 >= 0 ) {
if( index1 < 0 ){
nums1[mergeIndex--] = nums2[index2--];
}else if( index2 < 0){
nums1[mergeIndex--] = nums1[index1--];
}else if( nums1[index1] < nums2[index2] ){
nums1[mergeIndex--] = nums2[index2--];
}else{
nums1[mergeIndex--] = nums1[index1--];
}
}
}
}
网友评论