英文:
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 < 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 >= 0; i--) {
if (nums[i] == value) {
return i;
}
}
// the loop ended and we didn'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<Integer> 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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论