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;
}
}
Hello, welcome to Yizhe's Blog. I am Yizhe Liu, graduated from University of Arizona, with Master degree, major in Electrical and Computer Engineering. Actually, I am software guy. In my blog, many posts are about the Leetcode questions. I will post my ideas and implementations, which are accepted by Leetcode. If you have different opinions, please leave comment. I am happy to discuss with you. So lets start rocking them!!!
No comments:
Post a Comment