1.
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
HashMap<Integer,Integer> map = new HashMap<>();
int count = 0;
for (int i : nums1) {
for (int j : nums2) {
int temp = i + j;
if (map.containsKey(temp)) {
map.put(temp, map.get(temp) + 1);
} else {
map.put(temp, 1);
}
}
}
for (int i : nums3) {
for (int j : nums4) {
int temp = i + j;
if (map.containsKey(0 - temp)) {
count += map.get(0 - temp);
}
}
}
return count;
}
}
2.
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] map = new int[26];
for(char c : magazine.toCharArray()){
map[c-'a']++;
}
for(char c : ransomNote.toCharArray()){
map[c-'a']--;
}
for(int i : map){
if(i<0){
return false;
}
}
return true;
}
}
3
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ans = new ArrayList();
Arrays.sort(nums);
int i,j;
if(nums[0]>0 || nums.length<3){
return ans; //最小的数>0或者数字小于三个,直接返回空的ArrayList
}
for(int k=0;k<nums.length;k++){
if(k > 0 && nums[k] == nums[k-1]) continue; // 重复解
i = k+1;
j = nums.length - 1;
while(i<j){
int sum = nums[k]+nums[i]+nums[j];
if(sum==0){
ans.add(Arrays.asList(nums[k],nums[i],nums[j]));
while(i<j && nums[i] == nums[i+1]) i++;
while(i<j && nums[j] == nums[j-1]) j--;
i++;
j--;
}else if(sum>0){
j--;
}else if(sum<0){
i++;
}
}
}
return ans;
}
}
4.
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
// 剪枝
if (nums[i] > 0 && nums[i] > target) {
return result;
}
if (i > 0 && nums[i - 1] == nums[i]) { //nums[i]去重
continue;
}
for (int j = i + 1; j < nums.length; j++) {
if (j > i + 1 && nums[j - 1] == nums[j]) { //nums[j]去重
continue;
}
int left = j + 1;
int right = nums.length - 1;
while (right > left) {
//需要转化为long类型 否则会溢出
long sum = (long) nums[i] + nums[j] + nums[left] + nums[right];
if (sum > target) {
right--;
} else if (sum < target) {
left++;
} else { //等于target
result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
//nums[left]和nums[right]去重
while (right > left && nums[right] == nums[right - 1]) right--;
while (right > left && nums[left] == nums[left + 1]) left++;
left++;
right--;
}
}
}
}
return result;
}
}