class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
Map<Integer, Integer> map = new HashMap<>();
int temp;
int result = 0;
// 统计两个数组的元素之和, 并且同时统计出现的次数, 放入map
for (int i: nums1) {
for (int j: nums2) {
temp = i + j;
if (map.containsKey(temp)) {
map.put(temp, map.get(temp) + 1);
} else {
map.put(temp, 1);
}
}
}
// 统计剩余的两个元素的和, 在map中找到是否存在相加为0的情况, 同时记录次数
for (int i : nums3) {
for (int j : nums4) {
temp = i + j;
if (map.containsKey(0-temp)) {
result += map.get(0-temp);
}
}
}
return result;
}
}
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
// 对 magazine 进行词频统计
// 遍历 ransomNote 时对计数数组进行抵消操作
int[] words = new int[26];
for (char character : magazine.toCharArray()) {
words[character - 'a'] ++;
}
for (char character : ransomNote.toCharArray()) {
if (--words[character - 'a'] < 0) {
return false;
}
}
return true;
}
}
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> answer = new ArrayList();
int len = nums.length;
if (nums == null || len < 3) {
return answer;
}
Arrays.sort(nums);
for (int i = 0; i < len; i++) {
// 排序之后如果第一个大于0, 那么三个数字的和一定大于0, 直接结束循环
if (nums[i] > 0) {
break;
}
// 如果之前的数字被访问过, 直接跳过, 这一步去重
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[right] + nums[left];
if (sum == 0) {
answer.add(Arrays.asList(nums[i], nums[right], nums[left]));
// 去重
while (left < right && nums[left] == nums[left + 1]) {
left++;
}
// 去重
while (left < right && nums[right] == nums[right - 1]) {
right--;
}
left++;
right--;
} else if (sum < 0) {
left++;
} else if (sum > 0) {
right--;
}
}
}
return answer;
}
}
ref.力扣官方解题, 自己写没通过, 需要转换long再计算
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (nums == null || nums.length < 4) {
return result;
}
Arrays.sort(nums);
int length = nums.length;
for (int i = 0; i < length - 3; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
if ((long) nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) {
break;
}
if ((long) nums[i] + nums[length - 3] + nums[length - 2] + nums[length - 1] < target) {
continue;
}
for (int j = i + 1; j < length - 2; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
if ((long) nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) {
break;
}
if ((long) nums[i] + nums[j] + nums[length - 2] + nums[length - 1] < target) {
continue;
}
int left = j + 1, right = length - 1;
while (left < right) {
long sum = (long) nums[i] + nums[j] + nums[left] + nums[right];
if (sum == target) {
result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
while (left < right && nums[left] == nums[left + 1]) {
left++;
}
left++;
while (left < right && nums[right] == nums[right - 1]) {
right--;
}
right--;
} else if (sum < target) {
left++;
} else {
right--;
}
}
}
}
return result;
}
}