【问题标题】:How to to keep this merge array method in-bounds?如何保持这个合并数组方法在边界内?
【发布时间】:2015-03-30 15:39:07
【问题描述】:

我必须编写一个方法,将两个已经按升序排列的数组组合成一个按升序排序的数组。但是,它们的长度不同,因此递增会使它们超出范围。

Visualization

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;  
}

我需要解决什么问题才能使此方法有效?非常感谢!

【问题讨论】:

  • 你从哪里得到outofbounds异常?
  • 跳出循环后,将剩余元素(来自数组之一)添加到最终数组
  • 在最后一次迭代中,由于数组可以有不同的长度,所以会抛出异常。问题是如果我没有steps&lt;arr.length&amp;&amp;index_1&lt;nums1.length&amp;&amp;index_2&lt;nums2.length,那么它将超出范围,但这样做不会完成,因为其中一个条件为假将结束循环。如果您查看可视化的最后几个步骤,您会看到它发生了什么。
  • 只有当你 don't have that condition 你得到异常。所以你必须清楚地告诉你你的问题是什么

标签: java arrays indexing merge indexoutofboundsexception


【解决方案1】:

跳出循环后,将剩余元素(来自数组之一)添加到最终数组

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++;
}

【讨论】:

    猜你喜欢
    • 2015-07-21
    • 1970-01-01
    • 1970-01-01
    • 2018-08-20
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 2012-10-23
    相关资源
    最近更新 更多