|
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 | + |
8 | 9 | class Solution {
|
9 | 10 | 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); |
18 | 20 | }
|
19 |
| - return new int[]{}; |
| 21 | + |
| 22 | + throw new IllegalArgumentException(); |
20 | 23 | }
|
21 | 24 | }
|
0 commit comments