Two Sum
1. Two Sum
167. Two Sum II - Input array is sorted
Solve by using TreeSet instead of map to find the max sum under K.
public int twoSumLessThanK(int[] A, int K) {
TreeSet<Integer> set = new TreeSet<>();
int max = Integer.MIN_VALUE;
for (int i = 0; i < A.length; i++) {
if (set.lower(K - A[i]) != null) {
max = Math.max(max, set.lower(K - A[i]) + A[i]);
}
set.add(A[i]);
}
return max == Integer.MIN_VALUE ? -1 : max;
}Use if (i > 0 && nums[i] == nums[i - 1]) continue and while (left < right && nums[left] == nums[left + 1]) left++ etc to remove duplicates.
public List<List<Integer>> threeSum(int[] nums) {
if (nums == null || nums.length < 2) return new ArrayList<>();
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
int n = nums.length;
for (int i = 0; i < n - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int target = -nums[i];
int left = i + 1, right = n - 1;
while (left < right) {
if (nums[left] + nums[right] == target) {
result.add(Arrays.asList(nums[i], nums[left], nums[right]));
while (left < right && nums[left] == nums[left + 1]) left++;
while (left < right && nums[right] == nums[right - 1]) right--;
left++;
right--;
} else if (left < right && nums[left] + nums[right] < target) {
left++;
} else if (left < right && nums[left] + nums[right] > target) {
right--;
}
}
}
return result;
}Given a sorted list of numbers and a target Z, return the number of pairs according to following definition: (X,Y) where X+Y >= Z
Example 1:
Input: arr = [1, 3, 7, 9, 10, 11], Z = 7
Output: 14
18. 4Sum
170. Two Sum III - Data structure design
653. Two Sum IV - Input is a BST
4Sum / kSum
Last updated
Was this helpful?