When I first saw this question, it seems to take O(n^2) if a normal algorithm was used. However, try to take use of HashMap to store index and check whether what you want is in the array. Totally the following algorithm just need O(n) time
public class Solution {
public int[] twoSum(int[] numbers, int target) {
HashMap<Integer,Integer> numIdxMap = new HashMap<Integer,Integer>();
// Pre-process
for(int i = 0; i < numbers.length; i ++){
int remain = target - numbers[i];
numIdxMap.put(remain,i);
}
int[] result = new int[2];
for(int i = 0; i < numbers.length; i++){
int num = numbers[i];
if(numIdxMap.containsKey(num)){
int idx = numIdxMap.get(num);
if((num*2) == target && idx == i){
continue;
}
else{
if(idx > i){
result[0] = i+1;
result[1] = idx+1;
}
else{
result[0] = idx+1;
result[1] = i+1;
}
break;
}
}
}
return result;
}
}
No comments:
Post a Comment