File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed
Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change 1+ // https://leetcode.com/problems/two-sum/
2+
3+ class Solution {
4+ public int [] twoSum1 (int [] nums , int target ) {
5+
6+ /* BRUTE FORCE */
7+
8+ // Create a return list
9+ int [] ans = new int [2 ];
10+
11+ // Iterate nums
12+ for (int i = 0 ; i < nums .length ; i ++) {
13+ for (int j = i + 1 ; j < nums .length ; j ++) {
14+ if (nums [i ] + nums [j ] == target ) {
15+ ans [0 ] = i ;
16+ ans [1 ] = j ;
17+
18+ return ans ;
19+ }
20+ }
21+ }
22+
23+ return ans ;
24+ }
25+
26+ public int [] twoSum (int [] nums , int target ) {
27+
28+ /* HASH MAP APPROACH
29+ *
30+ * Time Complexity: O(n) = n is the length of nums.
31+ *
32+ * Space Complexity: O(n) = n is map size.
33+ */
34+
35+ // Create a hash map
36+ Map <Integer , Integer > map = new HashMap <>();
37+
38+ // Put all the elements to hash map
39+ for (int i = 0 ; i < nums .length ; i ++) {
40+ map .put (nums [i ], i );
41+ }
42+
43+ // Find the complement
44+ // I.e., nums[i] + X = target. X is the complement.
45+ for (int i = 0 ; i < nums .length ; i ++) {
46+ int complement = target - nums [i ];
47+
48+ // If complement exist in map and it isn't itself, then return list
49+ if (map .containsKey (complement ) && map .get (complement ) != i ) {
50+ return new int [] {map .get (complement ), i };
51+ }
52+ }
53+
54+ return null ;
55+ }
56+ }
You can’t perform that action at this time.
0 commit comments