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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> m = new HashMap<Integer,Integer>();
for(int i = 0;i < nums.length; ++i) {
int num = target - nums[i];
if(m.containsKey(num))
return new int[]{m.get(num), i };
m.put(nums[i], i);
}
throw new RuntimeException("no answer!");
}
思路:查找时,建立索引(Hash查找)或进行排序(二分查找)。本题缓存可在找的过程中建立索引,故一个循环可以求出解(总是使用未使用元素查找使用元素,可以保证每一对都被检索到)。Indexing/ordering is the first step to search questions.