目录
18. 4Sum
题目链接:https://leetcode.cn/problems/4sum/
方法一 二分 + 双指针
1 方法思想
2 代码实现
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
int len = nums.length;
List<List<Integer>> ans = new ArrayList<>();
if (nums == null || len < 4) return ans;
Arrays.sort(nums);
for (int j = 0; j < len; j++) {
if (j + 4 < len && (long) nums[j] + nums[j+1] + nums[j + 2] + nums[j + 3] > target) {
return ans;
}
if (j > 0 && nums[j - 1] == nums[j]) {
continue;
}
for (int i = j + 1; i < len; i++) {
if (i > j + 1 && nums[i] == nums[i - 1]) continue;
int left = i + 1;
int right = len - 1;
while (left < right) {
long sum = (long) nums[j] + nums[i] + nums[left] + nums[right];
if (sum == target) {
List<Integer> temp = new ArrayList<>();
temp.add(nums[j]);
temp.add(nums[i]);
temp.add(nums[left]);
temp.add(nums[right]);
ans.add(temp);
left++;
right--;
while (left < right && nums[left] == nums[left - 1]) {
left++;
}
while (left < right && nums[right] == nums[right + 1]) {
right--;
}
} else if (sum < target) {
left++;
} else {
right--;
}
}
}
}
return ans;
}
}
3 复杂度分析
时间复杂度:
空间复杂度:
4 涉及到知识点
15. 3Sum
题目链接:https://leetcode.cn/problems/3sum/
方法一 双指针
1 方法思想
2 代码实现
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
int len = nums.length;
if (nums == null || len < 3) return null;
List<List<Integer>> ans = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0; i < len; i++) {
if (nums[i] > 0) {
return ans;
}
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1;
int right = len - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
List<Integer> temp = new ArrayList<>();
temp.add(nums[i]);
temp.add(nums[left]);
temp.add(nums[right]);
ans.add(temp);
left++;
right--;
while (left < right && nums[left] == nums[left - 1]) {
left++;
}
while (left < right && nums[right] == nums[right + 1]) {
right--;
}
} else if (sum < 0) {
left++;
} else {
right--;
}
}
}
return ans;
}
}
3 复杂度分析
时间复杂度:
空间复杂度:
4 涉及到知识点
383. Ransom Note
题目链接:https://leetcode.cn/problems/ransom-note/
方法一
1 方法思想
2 代码实现
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] ascii = new int[26];
for (int i = 0; i < magazine.length(); i++) {
ascii[magazine.charAt(i) - 'a'] ++;
}
for (int i = 0; i < ransomNote.length(); i++) {
if (ascii[ransomNote.charAt(i) - 'a'] > 0 ){
ascii[ransomNote.charAt(i) - 'a'] --;
}else {
return false;
}
}
return true;
}
}
3 复杂度分析
时间复杂度:
空间复杂度:
4 涉及到知识点
454. 4Sum II
题目链接:https://leetcode.cn/problems/4sum-ii/
方法一
1 方法思想
2 代码实现
class Solution {
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
Map<Integer, Integer> countAB = new HashMap<Integer, Integer>();
for (int u : A) {
for (int v : B) {
countAB.put(u + v, countAB.getOrDefault(u + v, 0) + 1);
}
}
int ans = 0;
for (int u : C) {
for (int v : D) {
if (countAB.containsKey(-u - v)) {
ans += countAB.get(-u - v);
}
}
}
return ans;
}
}