两数之和
有没有一种数据结构可以即保存数据本身,又可以保存他的索引值呢? map! 没毛病!利用map的特性我们开始整理思路
搞一个map
遍历我们可爱的数组nums
在遍历的时候试图从map中找寻target-x的key,如果不存在就在我们的map中存入<数X,数X的索引>,存在的话就直接return
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
if(map.containsKey(nums[i])){
return new int[]{map.get(nums[i]), i};
}
map.put(target - nums[i], i);
}
return null;
}
}