Problem : Find two elements in an array whose sum is x.
Following is the implementation:
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
package hashTables.problems; | |
import java.util.HashMap; | |
import java.util.Map; | |
public class TwoSum { | |
public static int[] twoSum(int[] a, int x) { | |
int n = a.length; | |
Map<Integer,Integer> m = new HashMap(); | |
for(int i=0;i<n;i++) { | |
int k = a[i]; | |
int other = x-k; | |
if(m.containsKey(other)) { | |
return new int[] {other,k}; | |
}else { | |
m.put(k, i); | |
} | |
} | |
return new int[] {}; | |
} | |
public static void main(String[] args) { | |
int[] a = {1, 35, 4, 6, 10, 11}; | |
int x = 16; | |
int[] y = twoSum(a, x); | |
for(int i:y) { | |
System.out.println(i); | |
} | |
} | |
} |
No comments:
Post a Comment