leetcode/hash-table/TwoSum.java
See original GitHub issueThere is a better solution for the TwoSum problem than the hashmap solution. Sure hashmap is fine and meets the desired output. however it can be completely eliminated as such. The techinque employs a pointers to track the argument array i.e. one from the begining aka head
and the other one from the end aka tail
. A single sweep on the array and adjusting the two pointers does the job rather nicely.
//input array must be sorted
int head =0; int tail = arr.length -1; int k = 11; //target sum to find
while(head < tail) {
int sum = arr[head] + arr[tail];
if(sum == k) return true; //found it !!
else if(sum < k) ++head;
else --tail;
}
Issue Analytics
- State:
- Created 5 years ago
- Comments:6 (1 by maintainers)
Top Results From Across the Web
[Java] Hash table implementation: (Accepted Solution)
Here's my solution for the Two Sum problem using a Hash table. Adding each element to the Hash table takes linear time (O(n))....
Read more >LeetCode[Tree]: Binary Search Tree Iterator - CSDN博客
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
May be this is not completely related to the discussion. But with hash map and tuple together, we can solve this problem easily.
https://github.com/vin0010/Competitve-Programming/blob/master/python/leetcode/TwoSum.py
@sragha45 Yes, you are correct. But O(NlogN) is the worst case scenario when we have a very poor implementation of hash code which will map all entries to same bucket.
Have a look at the performance of hashmap in average case. https://dzone.com/articles/hashmap-performance