-
Notifications
You must be signed in to change notification settings - Fork 0
/
Q1_TwoSum.java
67 lines (55 loc) · 1.79 KB
/
Q1_TwoSum.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.gyanblog.leetcode;
import java.util.HashMap;
import java.util.Map;
import com.gyanblog.utils.ArrayUtils;
import com.gyanblog.utils.RandomUtils;
/**
* For detailed explanation, see: https://www.gyanblog.com/gyan/coding-interview/leetcode-solutions-two-sum/
*/
public class Q1_TwoSum {
/**
* Runs in O(n^2)
*/
public int[] twoSum_bad(int[] nums, int target) {
int l = nums.length;
for (int i=0; i<l; i++) {
for (int j=i+1; j<l; j++) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
return null;
}
/**
* Runs in O(n)
*/
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hashMap = new HashMap<>();
int l = nums.length;
for (int i=0; i<l; i++) {
int pairValue = target-nums[i];
if (hashMap.containsKey(pairValue)) {
return new int[]{i, hashMap.get(pairValue)};
}
if (!hashMap.containsKey(nums[i])) {
hashMap.put(nums[i], i);
}
}
return null;
}
public static void main(String[] args) {
int[] nums = RandomUtils.getRamdomArray(10, 20);
System.out.println(ArrayUtils.toString(nums));
Q1_TwoSum twoSum = new Q1_TwoSum();
System.out.println("Finding 20");
int[] indices = twoSum.twoSum(nums, 20);
System.out.println(ArrayUtils.toString(indices));
System.out.println("Finding 30");
indices = twoSum.twoSum(nums, 30);
System.out.println(ArrayUtils.toString(indices));
System.out.println("Finding 10");
indices = twoSum.twoSum(nums, 10);
System.out.println(ArrayUtils.toString(indices));
}
}