【小熊刷題】Two Sum
阿新 • • 發佈:2019-02-18
寫在前面
今天終於下定決心刷題了,先從已有答案的leetcode刷起。寫在這裡督促自己 :)
Two Sum
*Difficulty: Easy, Frequency: High
Question:
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
My Solution
* Thoughts: assume
* I. hashtable: target-key->ary[i], value-> i
* II. sort ary -> binary search tree?? if no space should be involved?
public int[] twoSum(int[] nums, int target) {
int[] ret = {-1, -1};
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < nums.length; i++){
map.put(target-nums[i], i);
}
for(int i = 0; i < nums.length; i++){
if(map.containsKey(nums[i]) && map.get(nums[i]) != i){ //last time forgot to check the case the two index should not be the same, e.g. {}
ret[0] = i+1;
ret[1] = map.get(nums[i]) +1;
System.out.println("index1="+ ret[0] + ", index2="+ret[1]);
return ret;
}
}
return ret;
}
Standard Solution
public int[] twoSum(int[] numbers, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < numbers.length; i++) {
int x = numbers[i];
if (map.containsKey(target - x)) {
return new int[] { map.get(target - x) + 1, i + 1 };
}
map.put(x, i);
}
throw new IllegalArgumentException("No two sum solution");
}
Comments
- 如果有解,不需要用遍歷兩遍
- 如果無解,可throw exception : IllegalArgumentException(“…”)
Follow up
What if the given input is already sorted in ascending order? See Question [2. Two SumII – Input array is sorted].