454.四数相加II
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
// 创建一个哈希映射来存储nums1和nums2的可能以及它们的频率
Map<Integer,Integer> sumMap = new HashMap<>();
int count = 0; // 初始化计数器为0
// 计算nums1 和nums2的可能以及它们的频率
for(int num1 : nums1) {
for(int num2 : nums2) {
int sum = num1 + num2; //计算可能的和
// 如果这个和已经在map 中存在 则取出其频率并加1 否则设为1
sumMap.put(sum, sumMap.getOrDefault(sum, 0) + 1);
}
}
// 检查nums3 和nums4的可能的和是否可以使总和为0
for(int num3 : nums3){
for(int num4 : nums4){
int sum = num3 + num4;
count += sumMap.getOrDefault(-sum,0);
}
}
return count;
}
}
383. 赎金信
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
// 创建一个长度为26的数组 用来存储magazine中每个字符的频率
int arr[] = new int[26];
for(int i = 0; i < magazine.length();i++){
arr[magazine.charAt(i) - 'a']++; //magazine中的字符频率+1;
}
for(int i = 0; i < ransomNote.length(); i++){
// 获取ransomNote 中字符在magazine中的频率
int index = ransomNote.charAt(i) - 'a';
// 检查频率是否为0
if (arr[index] == 0){
return false; //如果为0 返回false
} else {
arr[index]--; // 如果不为0 则频率-1
}
}
return true;
}
}
15. 三数之和
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
if(nums == null || nums.length < 3) return result;
// 排序
Arrays.sort(nums);
for(int i = 0; i < nums.length; i++){
if(nums[i] > 0) break; // 如果当前数字大于0 则三数之和一定大于0 所以结束循环
if(i >0 && nums[i] == nums[i-1]) continue; // 去重
int L = i+1, R = nums.length - 1;
while(L < R){
int sum = nums[i] + nums[L] + nums[R];
if(sum == 0){
result.add(Arrays.asList(nums[i], nums[L], nums[R]));
while(L< R && nums[L] == nums[L+1]) L++; //去重
while(L< R && nums[R] == nums[R-1]) R--; //去重
L++;
R--;
}
else if(sum < 0) L++;
else if(sum > 0) R--;
}
}
return result;
}
}
18. 四数之和
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
// 先对数组进行排序
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
int n = nums.length;
// 第一层循环,遍历第一个数字
for (int i = 0; i < n - 3; i++) {
// 跳过重复的数字
if (i > 0 && nums[i] == nums[i - 1]) continue;
// 第二层循环,遍历第二个数字
for (int j = i + 1; j < n - 2; j++) {
// 跳过重复的数字
if (j > i + 1 && nums[j] == nums[j - 1]) continue;
// 使用双指针处理剩下的两个数字
twoSum(nums, i, j, target, res);
}
}
return res;
}
// 双指针函数
private void twoSum(int[] nums, int i, int j, int target, List<List<Integer>> res) {
int left = j + 1, right = nums.length - 1;
while (left < right) {
long sum = (long)nums[i] + nums[j] + nums[left] + nums[right];
if (sum == target) {
res.add(Arrays.asList(nums[i], nums[j], 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 (sum < target) {
// 如果和小于target,则需要增大和,所以left右移
left++;
} else {
// 如果和大于target,则需要减小和,所以right左移
right--;
}
}
}
}