力扣每日一题
作者:互联网
看到好多人在刷题,俺也来试试,看看能坚持多久
数组
public class SumOfTwoNumber {
public static void main(String[] args) {
int[] nums = {1,2,3,7,4};
int[] ints = twoSum(nums, 8);
System.out.println("["+ints[0]+","+ints[1]+"]");
}
static int[] twoSum(int[] nums, int target) {
int[] indexs = new int[2];
//建立k-v,将值存进去
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
Integer integer = Integer.valueOf(nums[i]);
if(map.containsKey(nums[i])){
indexs[0] = i;
indexs[1] = map.get(integer);
}
map.put(target - nums[i],i);
}
return indexs;
}
}
标签:map,nums,int,每日,力扣,static,ints,indexs 来源: https://blog.csdn.net/qq_45097501/article/details/116229631