【问题标题】:How to find the next available slot in an array?如何找到数组中的下一个可用插槽?
【发布时间】:2016-05-01 20:33:14
【问题描述】:

当我遇到这个问题时,我正在使用 CodingBat 练习,我无法完全正确。给定一个正整数数组,我必须创建一个长度为“count”的数组,其中包含原始数组中的第一个偶数。原始数组将至少包含“count”个偶数。我的代码在下面,虽然我知道第一个 if 语句下面的所有内容都不起作用,并且“counter”变量基本上没用。

public int[] copyEvens(int[] nums, int count) {
  int counter = 0;
  int[] countArr = new int [count];
  for (int i = 0; i < nums.length; i++) {
    if (nums[i] % 2 == 0) {
      //what to put here?
    }
  }
  return countArr;
}

任何帮助将不胜感激。

【问题讨论】:

  • 如果为 0 表示可用
  • 我没有在代码中看到问题

标签: java arrays


【解决方案1】:

以下不正确:

  if (i == count) {

这会检查 input 数组中的位置,而不是 output 数组中的位置,与 count.

【讨论】:

    【解决方案2】:
    public int[] copyEvens(int[] nums, int count) {
      int counter = 0;
      int[] countArr = new int [count];
      for (int i = 0; i < nums.length && counter < count; i++) 
        if ((nums[i] % 2) == 0) 
            countArr[counter++] = nums[i];
      return countArr;
    }
    

    学校的东西……对吧?

    【讨论】:

    • 已修复...您的退出条件错误,,,它必须是(计数器
    【解决方案3】:

    我认为你应该比较 counter... 从 0 开始 .. 所以你需要加 1 因为我很确定 count 不包括 0 作为索引。

    因此,

    if((counter+1) ==count)
    

    应该替换原来的。

    【讨论】:

      猜你喜欢
      • 2019-03-04
      • 1970-01-01
      • 1970-01-01
      • 2021-10-07
      • 2013-08-09
      • 1970-01-01
      • 1970-01-01
      • 2014-06-07
      • 1970-01-01
      相关资源
      最近更新 更多