Leetcode 1. Two Sum
题目:
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
解题思路:
相当于单词书中的abandone,一切的开始,开始的一切。
选择数据结构:HashMap
设置HashMap数据结构,关键确定key,value取值,key-nums[i] ,value-i
遇到的问题:输入[3,3] tartget=6 时,返回[0,0],原因没考虑到遍历自身元素要被排除
代码:
public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hashMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
hashMap.put(nums[i],i);
}
for (int i = 0; i < nums.length; i++) {
int temp = target - nums[i];
if (hashMap.containsKey(temp) && (hashMap.get(temp)!=i)){
return new int[]{i,hashMap.get(temp)};
}
}
return new int[]{};
}