454.四数相加II
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
Map<Integer, Integer> hashMap1 = new HashMap<>();
for (int i = 0; i < nums1.length; i++) {
for (int j = 0; j < nums2.length; j++) {
int sum1 = nums1[i] + nums2[j];
hashMap1.put(-sum1, hashMap1.getOrDefault(-sum1, 0) + 1);
}
}
int res = 0;
Set<Map.Entry<Integer, Integer>> entries = hashMap1.entrySet();
for (int i = 0; i < nums3.length; i++) {
for (int j = 0; j < nums4.length; j++) {
int sum3 = nums3[i] + nums4[j];
if (hashMap1.containsKey(sum3)) {
res += hashMap1.get(sum3);
}
}
}
return res;
}
}
383.赎金信
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
Map<String, Integer> hashMap = new HashMap<>();
String[] split = magazine.split("");
for (int i = 0; i < split.length; i++) {
hashMap.put(split[i], hashMap.getOrDefault(split[i], 0) + 1);
}
String[] ransomSplit = ransomNote.split("");
for (int i = 0; i < ransomSplit.length; i++) {
if (!hashMap.containsKey(ransomSplit[i]) || hashMap.get(ransomSplit[i]) <= 0) {
return false;
} else {
hashMap.put(ransomSplit[i], hashMap.get(ransomSplit[i]) - 1);
}
}
return true;
}
}
15.三数之和
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> list = new LinkedList<>();
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int j = i + 1, k = nums.length - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
if (sum < 0) {
j++;
} else if (sum > 0) {
k--;
} else {
List<Integer> linkedList = new LinkedList<>();
linkedList.add(nums[i]);
linkedList.add(nums[j]);
linkedList.add(nums[k]);
list.add(linkedList);
while (j < k && nums[j] == nums[j + 1]) {
j++;
}
while (j < k && nums[k] == nums[k - 1]) {
k--;
}
j++;
k--;
}
}
}
return list;
}
}
18.四数之和
package com.hehe.lei;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class Main {
public static void main(String[] args) {
int[] nums = {2, 2, 2, 2, 2};
List<List<Integer>> lists = new Solution().fourSum(nums, 8);
}
}
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
List<List<Integer>> list = new LinkedList<>();
for (int i = 0; i < nums.length - 3; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
for (int j = i + 1; j < nums.length - 2; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
int k = j + 1;
int l = nums.length - 1;
while (k < l) {
Long sum = Long.valueOf(nums[i]) + Long.valueOf(nums[j]) + Long.valueOf(nums[k]) + Long.valueOf(nums[l]);
if (sum < target) {
k++;
} else if (sum > target) {
l--;
} else {
List<Integer> linkedList = new LinkedList<>();
linkedList.add(nums[i]);
linkedList.add(nums[j]);
linkedList.add(nums[k]);
linkedList.add(nums[l]);
list.add(linkedList);
while (k < l && nums[k] == nums[k + 1]) {
k++;
}
while (k < l && nums[l] == nums[l - 1]) {
l--;
}
k++;
l--;
}
}
}
}
return list;
}
}