Skip to content

Commit 19e2142

Browse files
authored
Update 0001-two-sum.java
1 parent cd16480 commit 19e2142

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Easy/0001-two-sum.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,27 @@
1+
/**
2+
* Problem: 1. Two Sum
3+
* Difficulty: Easy
4+
* URL: https://leetcode.com/problems/two-sum/
5+
*
6+
* Approach:
7+
* - Use a HashMap to store visited numbers and their indices.
8+
* - Check if target - current exists in map.
9+
*
10+
* Time Complexity: O(n)
11+
* Space Complexity: O(n)
12+
*/
13+
14+
class Solution {
15+
public int[] twoSum(int[] nums, int target) {
16+
Map<Integer, Integer> map = new HashMap<>();
17+
for (int i = 0; i < nums.length; i++) {
18+
int complement = target - nums[i];
19+
if (map.containsKey(complement)) {
20+
return new int[] { map.get(complement), i };
21+
}
22+
map.put(nums[i], i);
23+
}
24+
return new int[] {};
25+
}
26+
}
127

0 commit comments

Comments
 (0)