Java 索引返回了错误的值,即1而不是0
当我用nums={3,2,4}target=6调试这段代码时,对于key=3,我得到的索引值是1而不是0?有人能告诉我为什么吗Java 索引返回了错误的值,即1而不是0,java,Java,当我用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<num
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;
}
}
主类{
公共int[]twoSum(int[]nums,int目标){
HashMap=newHashMap();
对于(int i=0;iHashMap
和HashSet
不保留插入顺序。如果要保留插入顺序,需要使用LinkedHashMap
和LinkedHashSet
可以将数组索引映射到初始循环中的值以保留它。这是我从leetcode获得的解决方案。您的问题是f修正hashmap本身时遇到了麻烦
public int[] twoSum(int[] arr, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < arr.length; ++i) {
map.put(arr[i], i);
}
for(int j = 0; j < arr.length; ++j) {
int compliment = target - arr[j];
if (map.containsKey(compliment) == true && map.get(compliment) != j){
return new int[] {map.get(compliment), j };
}
}
throw new IllegalArgumentException("No Target");
}
public int[]twoSum(int[]arr,int-target){
HashMap=newHashMap();
对于(int i=0;i
除非您需要仅由实现提供的方法,否则分配给接口类型是标准做法。因此Map Map=new HashMap()
是首选。与列表
和集合
相同。还要注意,您不需要在作业右侧的
之间指定内容类型。谢谢!稍后,我也知道了这一点。非常欢迎您。祝您成功!