Leetcode学习笔记:#1 Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
实现:
public int[] twoSum(int[] numbers, int target){
Map<Integer, Integer> m = new HashMap<Integer, Integer>();
for(int i = 0; i < numbers.length; i++){
if(m.get(tartget-nums[i] != null){
return new int[]{m.get(target-nums[i]),i};
}
m.put(nums[i],i);
}
return new in[]{0,0};
}
思路:
只需遍历一遍,在遍历的同时检查map中是否有nums[i]的补数,如果有,则将两个数的位置存入int中并返回,如果没有,则保存进入map中。