class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
Map<Integer,Integer>map=new HashMap<>();
int res=0;
for(int i=0;i<nums1.length;i++){
for(int j=0;j<nums2.length;j++){
int sumAB=nums1[i]+nums2[j];
if(map.containsKey(sumAB))
map.put(sumAB,map.get(sumAB)+1);
else
map.put(sumAB,1);
}
}
for(int i=0;i<nums3.length;i++){
for(int j=0;j<nums4.length;j++){
int sumCD=-(nums3[i]+nums4[j]);
if(map.containsKey(sumCD))
res+=map.get(sumCD);
}
}
return res;
}
}
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] cnt=new int[26];
for(int i=0;i<magazine.length();++i){
++cnt[magazine.charAt(i)-'a'];
}
for(int i=0;i<ransomNote.length();++i){
if(--cnt[ransomNote.charAt(i)-'a']<0){
return false;
}
}
return true;
}
}
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res=new ArrayList<>();
for(int k = 0; k < nums.length - 2; k++){
if(nums[k] > 0) break;
if(k > 0 && nums[k] == nums[k - 1]) continue;
int i = k + 1, j = nums.length - 1;
while(i < j){
int sum = nums[k] + nums[i] + nums[j];
if(sum < 0){
while(i < j && nums[i] == nums[++i]);
} else if (sum > 0) {
while(i < j && nums[j] == nums[--j]);
} else {
res.add(new ArrayList<Integer>(Arrays.asList(nums[k], nums[i],nums[j])));
while(i < j && nums[i] == nums[++i]);
while(i < j && nums[j] == nums[--j]);
}
}
}
return res;
}
}
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
int len = nums.length;
for(int i = 0; i < len - 3; i++) {
if (i > 0 && nums[i] == nums[i-1]) {
continue;
}
for (int j = i + 1; j < len - 2; j++) {
if (j > i + 1 && nums[j] == nums[j-1]) {
continue;
}
int left = j + 1;
int right = len - 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+1] == nums[left]) left++;
while (left < right && nums[right-1] == nums[right]) right--;
left++;
right--;
} else if (sum > target) {
right--;
} else {
left++;
}
}
}
}
return res;
}
}