1.两数求和 (two sum)
题目:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
class Solution {
/**
*核心思想:将所有数组中元素,放入map中key是元素值,value是元素索引位置
*从数组中遍历元素,遍历一个元素,让sum值减去这个元素得出值,然后去hashMap中去找是否有此值,并且不是 减去的这个元素
*找到,再根据get(key).获取索引,即可
*/
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap<>();
int[] res = new int[2];
if(nums!=null && nums.length>0) {
for (int i = 0; i < nums.length; ++i) {
map.put(nums[i], i);
}
for(int i = 0; i < nums.length; ++i) {
int left = target-nums[i];
if (map.containsKey(left) && map.get(left)!=i){
res[0] = i;
res[1] = map.get(left);
break;
}
}
}
return res;
}
}