TwoSum
1. 2 Sum
Return the indexes of sum equals to target 1. Hash table (target-num, index) 2. If we can find num in hash table, return
2 Sum Closest
2 numbers sum up closest to target, return the diff
sort array
public int twoSumClosest(int[] nums, int target) {
if (nums == null || nums.length < 2) {
return -1;
}
Arrays.sort(nums);
int left = 0, right = nums.length - 1;
int diff = Integer.MAX_VALUE;
while (left < right) {
if (nums[left] + nums[right] < target) {
diff = Math.min(diff, target - (nums[left] + nums[right]));
left++;
} else {
diff = Math.min(diff, nums[left] + nums[right] - target);
right--;
}
}
return diff;
}15. 3 sum
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Apply 2sum
16. 3 Sum Closest
Return the closest sum of integers
18. 4 Sum
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
4 Sum ll
Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.
Count the combination of a+b, n^2 loop, Hash table<-sum, times>
Check if c+d match and a+b match target, n^2 loop, count the sum of times
Whole minute dilemma
Given a list of song length, return the number of ways choose 2 songs that the total duration is multiple of whole minute.
remain = second % 60
residue = 60 - remaon
Map
653. Two Sum IV - Input is a BST
Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.
Inorder traverse to a list
Last updated
Was this helpful?