41. 缺失的第一个正数
class Solution {
public int firstMissingPositive(int[] nums) {
for(int i = 0; i < nums.length; i++) {
while(nums[i] > 0 && nums[i] <= nums.length && nums[i] != nums[nums[i] - 1] ) {
swap(nums, i, nums[i]-1);
}
}
for(int i = 0; i < nums.length; i++) {
if(nums[i] != i + 1) {
return i + 1;
}
}
return nums.length + 1;
}
private void swap (int[] nums, int index1, int index2) {
int temp = nums[index1];
nums[index1] = nums[index2];
nums[index2] = temp;
}
}
209. 长度最小的子数组
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int left = 0, right = 0;
int sum = 0;
int minLen = Integer.MAX_VALUE;
while(right < nums.length) {
sum += nums[right];
while(sum >= target) {
minLen = Math.min(minLen, right - left + 1);
sum -= nums[left];
left ++;
}
right ++;
}
return minLen = (minLen == Integer.MAX_VALUE) ? 0 : minLen;
}
}
39. 组合总和 – 回溯
拿到这个题目能够想到是回溯+剪枝,但是和没思路差不多,没有想到要先排序。另外回溯“模板”还是不熟练,导致coding不上来。前几天做过的题和没做差不多。。。。。。 class Solution { public List<List> combinationSum(int[] candidates, int target) { List<List> res = new ArrayList<>(); List path = new ArrayList<>(); //if (candidates.length == 0) return res; Arrays.sort(candidates); backtrack(candidates, target, res, path, 0); return res; } public void backtrack(int[] candidates, int target, List<List> res, List path, int begin) { if(target < 0) return; if(target == 0){ res.add(new ArrayList<>(path)); return; } for(int i = begin; i < candidates.length; i ++) { //剪枝 if(candidates[i] > target) return; if(i > 0 && candidates[i] == candidates[i-1]) continue; //回溯套路 path.add(candidates[i]); backtrack(candidates, target - candidates[i], res, path, i); path.remove(path.size()-1); } } }
|