Skip to content

Commit

Permalink
two sum java
Browse files Browse the repository at this point in the history
  • Loading branch information
GouravRusiya30 authored Jul 20, 2020
1 parent c2e6075 commit cbbead1
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions Java/two-sum.java
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);
}
}
}
}

0 comments on commit cbbead1

Please sign in to comment.