Shay
BAN USER
Comments (5)
Reputation 25
Page:
1
Comment hidden because of low score. Click to expand.
Comment hidden because of low score. Click to expand.
Comment hidden because of low score. Click to expand.
Comment hidden because of low score. Click to expand.
Comment hidden because of low score. Click to expand.
2
of 4 vote
public static void two_sum_problem(int arr[], int sum) {
// store all the elements of arr in a hashmap
HashMap hm = new HashMap();
for (int i = 0; i < arr.length; i++) {
hm.put(arr[i], arr[i]);
}
// go through the array, and check if the difference sum-arr[i] is in the hashmap
// if sum-arr[i] is in the hashmap, you have found two numbers that add upto sum.
for (int i = 0; i < arr.length; i++) {
int lookFor = sum - arr[i];
boolean hasValue = hm.containsValue(lookFor);
if (hasValue) {
System.out.println("Found: "+ arr[i] + "+" + lookFor + "=" + sum);
}
}
}
Page:
1
CareerCup is the world's biggest and best source for software engineering interview preparation. See all our resources.
This can be done in linear time and linear memory. Starting from the bottom left, with each move, you can eliminate one person as a candidate for an influencer.
- Shay May 15, 2014