-
-
Notifications
You must be signed in to change notification settings - Fork 424
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c2e6075
commit cbbead1
Showing
1 changed file
with
29 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
/** | ||
* One-pass Hash Table | ||
* we iterate and inserting elements into the table, | ||
* we also look back to check if current element's complement already exists in the table. | ||
* If it exists, we have found a solution and return immediately. | ||
* | ||
* Time complexity : O(n) | ||
* Space complexity : O(n) | ||
*/ | ||
class Solution { | ||
public int[] twoSum(int[] nums, int target) { | ||
|
||
Map<Integer, Integer> sumMap = new HashMap<>(); | ||
int [] result = new int[2]; | ||
|
||
for (int i=0; i<nums.length(); i++){ | ||
|
||
if(!sumMap.isEmpty() && sumMap.containsKey(nums[i])){ | ||
result[0] = sumMap.get(nums[i]); | ||
result[1] = i; | ||
|
||
return result; | ||
} | ||
else{ | ||
sumMap.put(target-nums[i],i); | ||
} | ||
} | ||
} | ||
} |