gpt4 book ai didi

java - 索引返回错误值,即 1 而不是 0

转载 作者:行者123 更新时间:2023-12-05 09:07:15 26 4
gpt4 key购买 nike

当我使用 nums={3,2,4} target = 6 调试此代码时,对于 key = 3,我得到的索引值为 1 而不是 0?有人可以告诉我为什么吗?

class Main {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++) {
map.put(nums[i],nums[i]);
}
Set<Integer> set = map.keySet();
ArrayList<Integer> list = new ArrayList<Integer>(set);

for(int i=0;i<nums.length-1;i++) {
if(map.containsKey(target-nums[i])) {
int key = map.get(target-nums[i]);
int index = list.indexOf(key);
if(index != i) {
nums = new int[2];
nums[0] = i;
nums[1] = index;
}
}
}
return nums;
}
}

最佳答案

HashMapHashSet 不维护插入顺序。如果要保留插入顺序,需要使用LinkedHashMapLinkedHashSet

关于java - 索引返回错误值,即 1 而不是 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65204788/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com