题目:
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.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
看到题目,很容易就想出来的一种解法:
-
public class Solution {
-
public int[] twoSum(int[] numbers, int target) {
-
int[] result = new int[2];
-
int len = numbers.length;
-
for(int i = 0; i < len; i++){
-
for(int j = i+1; j < len; j++){
-
if(numbers[i]+numbers[j] == target){
-
result[0] = i+1;
-
result[1] = j+1;
-
}
-
}
-
return result;
-
}
-
}
但是将这种解法提交到OJ的话是不会通过的,原因在于算法的复杂度过高。而采用hashset的话可以将算法的复杂度大大降低,程序如下:
-
public class Solution {
-
public int[] twoSum(int[] numbers, int target) {
-
int[] result = new int[2];
-
int len = numbers.length;
-
HashMap<Integer,Integer> myhashmap = new HashMap<Integer,Integer>();
-
for(int i = 0; i < len; i++){
-
Integer diff = Integer.valueOf(target - numbers[i]);
-
if(myhashmap.containsKey(diff)){
-
result[0] = myhashmap.get(diff);
-
result[1] = i+1;
-
}
-
myhashmap.put(Integer.valueOf(numbers[i]), Integer.valueOf(i+1));
-
}
-
return result;
-
}
-
}
阅读(604) | 评论(0) | 转发(0) |