Skip to content

Instantly share code, notes, and snippets.

@sreeprasad
Created October 4, 2014 17:27
Show Gist options
  • Save sreeprasad/29a5056f1b4eeb39773c to your computer and use it in GitHub Desktop.
Save sreeprasad/29a5056f1b4eeb39773c to your computer and use it in GitHub Desktop.
Two Sum
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