Skip to content

Commit 8ca1cc0

Browse files
committed
feat: two sum
1 parent e05461f commit 8ca1cc0

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

two-sum/minji-go.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
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+
*/
8+
class Solution {
9+
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+
}
18+
}
19+
return new int[]{};
20+
}
21+
}

0 commit comments

Comments
 (0)