我必须编写一种方法,将两个已经按升序排列的数组组合成一个按升序排列的数组。然而,它们的长度不同,因此递增会使它们超出范围。
int[] mergeTwo(int[] nums1, int[] nums2) {
int[] arr = new int[nums1.length+nums2.length];
int index_1=0;
int index_2=0;
int content_1=0;
int content_2=0;
for(int steps=0;steps<arr.length&&index_1<nums1.length&&index_2<nums2.length;steps++) {
content_1=nums1[index_1];
content_2=nums2[index_2];
if(content_1<content_2) {
arr[steps]=content_1;
index_1++;
}
if(content_1>content_2) {
arr[steps]=content_2;
index_2++;
}
}
return arr;
}
我需要修复什么才能使此方法发挥作用?非常感谢!
最佳答案
跳出循环后,将剩余元素(来自数组之一)添加到最终数组
while(index_1 < nums1.length)
{
arr[steps] = nums1[index_1];
index_1++;
steps++;
}
while(index_2 < nums2.length)
{
arr[steps] = nums2[index_2];
index_2++;
steps++;
}
关于java - 如何保持这个合并数组方法在边界内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28248145/