1. 两数之和
排除暴力解法,采用map的解法:
map的key值为元素值,value为在数组中的索引。
思路:1.遍历一遍数组,查看target - 当前元素值是否在map中存在,如果存在在返回当前遍历的数组索引和得到的map的value值
2. 不存在则将当前元素按<元素值,索引>的形式保存在map中。
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
int[] result = new int[2];
for (int i = 0; i < nums.length; i++) {
if(map.get(target - nums[i])!=null)
{
result[0] = i;
result[1] = map.get(target - nums[i]);
return result;
}
map.put(nums[i],i);
}
return null;
}
}