返回数组中值的最后一个索引

huangapple go评论76阅读模式
英文:

Returning the last index of a value in an array

问题

我遇到了这个问题,要求我返回数组中某个值的最后一个索引。目前这是我的代码,我只需要知道应该返回什么。

public int lastIndexOf(int[] nums, int value) {
    for (int i = nums.length - 1; i >= 0; i--) {
        if (nums[i] == value) {
            return i;
        }
    }
    return -1;
}
英文:

I am having trouble with this problem that is asking me to return the last index of a value in an array. This is my code so far, I just need help knowing what to return

public int lastIndexOf(int[] nums, int value) {
    for (int i : nums) {
        if (i == value) {
            return;
        } else  {
            return -1;
        }
    }
}

答案1

得分: 2

你的代码永远不会起作用;它会在访问数组的第一个元素后返回结果,而不是访问每个元素。

我建议你这样做:

public int lastIndexOf(int[] nums, int value) {
    int index = -1;
    for (int i = 0; i < nums.length; i++)
        if (nums[i] == value)
            index = i;

    return index;
}
英文:

Your code will never work; it will return the result after visiting the first element of your array instead of visiting each element.

I would suggest you to do that:

public int lastIndexOf(int[] nums, int value) {
    int index = -1;
    for (int i = 0; i &lt; nums.length; i++)
        if (nums[i] == value)
            index = i;

    return index;
}

答案2

得分: 2

你可以考虑从数组末尾开始遍历,这样一旦找到所需寻找的最右元素,就可以立即返回。

public int lastIndexOf(int[] nums, int value) {
    for (int i = nums.length - 1; i >= 0; i--) {
        if (nums[i] == value) {
            return i;
        }
    }
    // 循环结束,我们没有找到目标元素
    return -1;
}
英文:

You may want to traverse the array backwards, so you can return as soon as you find the right-most element you're looking for.

public int lastIndexOf(int[] nums, int value) {
    for (int i = nums.length - 1; i &gt;= 0; i--) {
        if (nums[i] == value) {
            return i;
        }
    }
    // the loop ended and we didn&#39;t find anything
    return -1;
}

答案3

得分: 2

使用stream()、Collections.reverse()和indexOf()的另一种方法

public int lastIndexOf(int[] nums, int value) {
    List<Integer> numsList = Arrays.stream(nums).boxed().collect(Collectors.toList());
    Collections.reverse(numsList); // 现在列表已经反转
    return numsList.indexOf(value) == -1 ? -1 : numsList.size() - numsList.indexOf(value) - 1;
}
英文:

An alternative using stream(), Collections.reverse() and indexOf()

public int lastIndexOf(int[] nums, int value) {
    List&lt;Integer&gt; numsList = Arrays.stream(nums).boxed().collect(Collectors.toList());
    Collections.reverse(numsList); // now the list is reversed
    return numsList.indexOf(value) == -1 ? -1 : numsList.size() - numsList.indexOf(value) - 1;
}

huangapple
  • 本文由 发表于 2020年9月30日 04:41:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/64127338.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定