您的位置:首页 > 其它

Merge Sorted Array

2015-11-15 14:29 281 查看

题目描述

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.

题目解答

解题思路

合并两个有序的数组,并且放在其中一个数组中,我们可以从尾部开始选取最大值,然后填充在最后面,即比较两个数组中的最大值,每次选取最大的放在数组的尾部。

代码实现

public class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
if(m == 0 && n == 0)
return ;

int leftS1 = 0, rightS1 = m-1;
int leftS2 = 0, rightS2 = n-1;
int i = n+m-1;
while(leftS1 <= rightS1 && leftS2 <= rightS2){
if(nums1[rightS1] > nums2[rightS2]){
nums1[i] = nums1[rightS1];
rightS1--;
}else {
nums1[i] = nums2[rightS2];
rightS2--;
}
i--;
}
while(leftS2 <= rightS2) {
nums1[i] = nums2[rightS2];
rightS2--;
i--;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: