头尾两个pointer解决ksum类型问题
以求数组里两个数相加等于target(2sum)为例
首先将数组nums排序
用两个下标分别从nums[0]和nums[nums.length-1]开始往中间移动,逐渐接近target
Knum的解法相同,只是先降为(k-1)num, 时间复杂度为N^(k-1)
数组中三个数相加结果为target:
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ret = new LinkedList<>();
Arrays.sort(nums);
for(int i=0; i<nums.length-2; i++) {
if(i != 0 && nums[i]==nums[i-1]) continue;
int low = i+1;
int high = nums.length-1;
while(low < high) {
int t = nums[low]+nums[high];
if(t < -nums[i]) {
low++;
}
else if(t > -nums[i]) {
high--;
}
else {
ret.add(Arrays.asList(nums[i],nums[low],nums[high]));
while(low<high&&nums[low]==nums[low+1]) low++;
while(low<high&&nums[high]==nums[high-1]) high--;
low++;
high--;
}
}
}
return ret;
}
}
Array标签
https://leetcode.com/tag/array/
二分查找解决rotated sorted array问题
https://leetcode.com/problems/search-in-rotated-sorted-array/
回溯法解combination sum. subset等问题
回溯法解Subsets, Permutations, Combination Sum, Palindrome Partitioning