Skip to content

Commit 89c289f

Browse files
committed
feat: two-sum
1 parent 5ae6bd7 commit 89c289f

File tree

1 file changed

+19
-16
lines changed

1 file changed

+19
-16
lines changed

two-sum/minji-go.java

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,24 @@
1-
/*
2-
Problem: https://leetcode.com/problems/two-sum/
3-
Description: return indices of the two numbers such that they add up to target. not use the same element twice.
4-
Topics: Array, Hash Table
5-
Time Complexity: O(N), Runtime 2ms
6-
Space Complexity: O(N), Memory 45.1MB
7-
*/
1+
/**
2+
* <a href="https://leetcode.com/problems/two-sum/">week01-2.two-sum</a>
3+
* <li> Description: return indices of the two numbers such that they add up to target. not use the same element twice. </li>
4+
* <li> Topics: Array, Hash Table </li>
5+
* <li> Time Complexity: O(N), Runtime 2ms </li>
6+
* <li> Space Complexity: O(N), Memory 45.4MB </li>
7+
*/
8+
89
class Solution {
910
public int[] twoSum(int[] nums, int target) {
10-
Map<Integer, Integer> numIndex = new HashMap<>();
11-
for(int secondIndex=0; secondIndex<nums.length; secondIndex++){
12-
if(numIndex.containsKey(target-nums[secondIndex])){
13-
int firstIndex = numIndex.get(target-nums[secondIndex]);
14-
return new int[]{firstIndex, secondIndex};
15-
} else {
16-
numIndex.put(nums[secondIndex], secondIndex);
17-
}
11+
Map<Integer, Integer> seen = new HashMap<>();
12+
13+
for (int i = 0; i < nums.length; i++) {
14+
int num = target - nums[i];
15+
16+
if (seen.containsKey(num))
17+
return new int[]{seen.get(num), i};
18+
19+
seen.put(nums[i], i);
1820
}
19-
return new int[]{};
21+
22+
throw new IllegalArgumentException();
2023
}
2124
}

0 commit comments

Comments
 (0)