15睬塌、3Sum
Example
given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
復雜度
時間 O(N^2) 空間 O(1)
思路
雙指針法
3Sum其實可以轉化成一個2Sum的題颖御,先從數(shù)組中選一個數(shù),并將目標數(shù)減去這個數(shù)嘲更,得到一個新目標數(shù)筐钟。
然后再在剩下的數(shù)中找一對和是這個新目標數(shù)的數(shù),其實就轉化為2Sum了赋朦。
為了避免得到重復結果篓冲,不僅要跳過重復元素,而且要保證2Sum找的范圍要是在最先選定的那個數(shù)之后的宠哄。
解法
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
ArrayList<List<Integer>> res = new ArrayList<List<Integer>>();
for(int i = 0; i < nums.length - 2; i++){
// 跳過重復元素
if(i > 0 && nums[i] == nums[i-1]) continue;
// 計算2Sum
ArrayList<List<Integer>> curr = twoSum(nums, i, 0 - nums[i]);
res.addAll(curr);
}
return res;
}
private ArrayList<List<Integer>> twoSum(int[] nums, int i, int target){
int left = i + 1, right = nums.length - 1;
ArrayList<List<Integer>> res = new ArrayList<List<Integer>>();
while(left < right){
if(nums[left] + nums[right] == target){
ArrayList<Integer> curr = new ArrayList<Integer>();
curr.add(nums[i]);
curr.add(nums[left]);
curr.add(nums[right]);
res.add(curr);
do {
left++;
}while(left < nums.length && nums[left] == nums[left-1]);
do {
right--;
} while(right >= 0 && nums[right] == nums[right+1]);
} else if (nums[left] + nums[right] > target){
right--;
} else {
left++;
}
}
return res;
}
}
18壹将、4Sum
Example
Given array S = {1 0 -1 0 -2 2}, and target = 0.
A solution set is:
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)
解法
public class Solution {
public ArrayList<ArrayList<Integer>> fourSum(int[] A, int target) {
int n = A.length;
ArrayList<ArrayList<Integer>> res = new ArrayList();
Arrays.sort(A);
for (int i = 0; i < n-3; i++) {
if (i != 0 && A[i] == A[i-1]) continue;
for (int j = i+1; j <= n-3; j++) {
if (j != i+1 && A[j] == A[j-1]) continue;
int left = j+1, right = n-1;
while (left < right) {
int sum = A[i]+A[j]+A[left]+A[right];
if (sum == target) {
ArrayList<Integer> temp = new ArrayList();
temp.add(A[i]);
temp.add(A[j]);
temp.add(A[left]);
temp.add(A[right]);
res.add(temp);
left++;
right--;
while (left < right && A[left] == A[left-1]) left++;
while (left < right && A[right] == A[right+1]) right--;
}
else if (sum < target) left++;
else right--;
}
}
}
return res;
}
}