[LeetCode][167. Two Sum II - Input Array Is Sorted] 4 Approaches: Brute Force, HashMap, Binary Search, Two Pointers
By Long Luo
This article is the solution 4 Approaches: Brute Force, HashMap, Binary Search, Two Pointers of Problem 167. Two Sum II - Input Array Is Sorted .
Here shows 4 Approaches to slove this problem: Brute Force, HashMap, Binary Search, Two Pointers.
Brute Force
It’s easy to use Brute Force to find the answer, however, the time complexity is
1 | public static int[] twoSum_bf(int[] numbers, int target) { |
Analysis
- Time Complexity:
. - Space Complexity:
.
HashMap
We can use a extra
1 | public static int[] twoSum_hash(int[] numbers, int target) { |
Analysis
- Time Complexity:
. - Space Complexity:
.
Binary Search
Since the array is already sorted, so we can use the binary search. In case of duplicated answer, we search only on the right of the left element.
1 | public int[] twoSum_bs(int[] numbers, int target) { |
Analysis
- Time Complexity:
. - Space Complexity:
.
Two Pointers
- Let the two pointers point to the position of the first element and the position of the last element;
- Each time the sum of the two elements pointed to by the two pointers is calculated and compared with the target value.
- A unique solution is found if the sum of the two elements equals the target value.
- If the sum of the two elements is less than the target, move the left pointer to the right one place; If the sum of the two elements is greater than the target, move the right pointer to the left by one.
- Repeat until you find the answer.
1 | public static int[] twoSum_tp(int[] numbers, int target) { |
Analysis
- Time Complexity:
. - Space Complexity:
.
All suggestions are welcome. If you have any query or suggestion please comment below. Please upvote👍 if you like💗 it. Thank you:-)
Explore More Leetcode Solutions. 😉😃💗
预览: