Skip to content

Commit 3b3bb55

Browse files
authored
Add files via upload
1 parent f7e7fa2 commit 3b3bb55

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Hash Table/Two_Sum.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
//LeetCode 1. Two Sum
2+
//Question Link - https://leetcode.com/problems/two-sum/
3+
4+
class Solution {
5+
public int[] twoSum(int[] nums, int target) {
6+
int result[] = new int[2];
7+
8+
//to store the numbers which have already been encountered
9+
//key = number in array, value = index of the number
10+
Map<Integer, Integer> seen = new HashMap<>();
11+
12+
for(int i = 0 ; i < nums.length ; i++){
13+
//the number nums[i] is alreday in the array
14+
//check if (target - nums[i]) is also in the array or not
15+
int complement = target - nums[i];
16+
17+
//we check if we have already encountered complement or not.
18+
if(seen.containsKey(complement)){
19+
return new int[]{seen.get(complement), i};
20+
}
21+
22+
//if complement does not exsist, we must store the current number in seen
23+
//The current number could be the complement of some number to be visited further in the array
24+
seen.put(nums[i], i);
25+
}
26+
27+
return result;
28+
}
29+
}

0 commit comments

Comments
 (0)