We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent b3d6f06 commit 84464f9Copy full SHA for 84464f9
1 file changed
Math/TwoSum.java
@@ -0,0 +1,33 @@
1
+class TwoSum {
2
+ public int[] twoSumBrute(int[] nums, int target) { // brute-force O(n^2) time
3
+ int n = nums.length;
4
+ int[] result = new int[2];
5
+ for(int i = 0; i<n; i++){
6
+ for(int j = 0; j<n; j++){
7
+ if((nums[i]+nums[j]) == target && (i!=j)){
8
+ result[0] = i;
9
+ result[1] = j;
10
+ return result;
11
+ }
12
13
14
15
+
16
+ public int[] twoSumHash(int[] nums, int target) { // 1-Hash approach O(n) time
17
+ Map<Integer, Integer> map = new HashMap<>();
18
19
20
+ for(int i = 0; i<nums.length; i++){
21
+ int complement = target-nums[i];
22
+ if(map.containsKey(complement) && map.get(complement)!= i){
23
24
+ result[1] = map.get(complement);
25
26
27
+ map.put(nums[i], i);
28
29
30
31
32
+}
33
0 commit comments