Skip to content

Commit cbbead1

Browse files
two sum java
1 parent c2e6075 commit cbbead1

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Java/two-sum.java

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* One-pass Hash Table
3+
* we iterate and inserting elements into the table,
4+
* we also look back to check if current element's complement already exists in the table.
5+
* If it exists, we have found a solution and return immediately.
6+
*
7+
* Time complexity : O(n)
8+
* Space complexity : O(n)
9+
*/
10+
class Solution {
11+
public int[] twoSum(int[] nums, int target) {
12+
13+
Map<Integer, Integer> sumMap = new HashMap<>();
14+
int [] result = new int[2];
15+
16+
for (int i=0; i<nums.length(); i++){
17+
18+
if(!sumMap.isEmpty() && sumMap.containsKey(nums[i])){
19+
result[0] = sumMap.get(nums[i]);
20+
result[1] = i;
21+
22+
return result;
23+
}
24+
else{
25+
sumMap.put(target-nums[i],i);
26+
}
27+
}
28+
}
29+
}

0 commit comments

Comments
 (0)