1.Two sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
Solution: First think binary search. Might not be a good solution since it needs first to be sort O(NlogN), Then search O(nlogn).
HashMap may be a good way.
1 | public int[] twoSum(int[] nums, int target) { |
2.Three Sum
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Solution: Brute force would be O(N^3).
In whatever way we must traverse firstly to ensure one number, then the problem would be two sum.
Hashset:O(N*N)
Sort+Two pointers: O(NlogN+N^n)