We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent c2e6075 commit cbbead1Copy full SHA for cbbead1
Java/two-sum.java
@@ -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