Created
October 4, 2014 17:27
-
-
Save sreeprasad/29a5056f1b4eeb39773c to your computer and use it in GitHub Desktop.
Two Sum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public int[] twoSum(int[] numbers, int target) { | |
int [] index = new int[2]; | |
if(numbers.length==0) | |
return index; | |
int N = numbers.length; | |
HashMap<Integer,Integer> map = new HashMap<Integer, Integer>(); | |
for(int i=0;i<N;i++){ | |
map.put(numbers[i],i); | |
} | |
for(int i=0;i<N;i++){ | |
int index1 =i; | |
int v1= numbers[i]; | |
int v2 = target-v1; | |
if( map.containsKey(v2) && map.get(v2)!=i ){ | |
index[0]=index1+1; | |
index[1]=map.get(v2)+1; | |
return index; | |
} | |
} | |
return index; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment