454:
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
Map<Integer, Integer> map = new HashMap<>();
for(int a : nums1){
for(int b : nums2){
int temp = a + b;
map.put(temp, map.getOrDefault(temp, 0) + 1);
}
}
int res = 0;
for(int c : nums3){
for(int d : nums4){
int temp = c + d;
res += map.getOrDefault(-c-d, 0);
}
}
return res;
}
}
383:
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] alphabet = new int[26];
if(ransomNote.length() > magazine.length()) return false;
for(int i = 0; i < magazine.length(); i++){
// map.put(magazine.charAt(i), 1 + getOrDefault(magazine.charAt(i), 0));
alphabet[magazine.charAt(i) - 'a'] += 1;
}
for(int i = 0; i < ransomNote.length(); i++){
alphabet[ransomNote.charAt(i) - 'a'] -= 1;
if(alphabet[ransomNote.charAt(i) - 'a'] < 0){
return false;
}
}
return true;
}
}
15:
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
// int a = 0, b = a + 1, c = nums.length - 1;
for(int a = 0; a < nums.length; a++){
if(nums[a] > 0) return res;
if(a > 0 && nums[a] == nums[a - 1]) return res;
int b = a + 1;
int c = nums.length - 1;
while(b < c){
if(nums[a] + nums[b] + nums[c] < 0){
b++;
}else if(nums[a] + nums[b] + nums[c] > 0){
c--;
}else{
List<Integer> temp = new ArrayList<>();
temp.add(nums[a]);
temp.add(nums[b]);
temp.add(nums[c]);
res.add(temp);
while(b < c && nums[c] == nums[c - 1]) c--;
while(b < c && nums[b] == nums[b + 1]) b++;
b++;
c--;
}
}
}
return res;
}
}
18:
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]) {
continue;
}
for (int j = i + 1; j < nums.length; j++) {
if (j > i + 1 && nums[j - 1] == nums[j]) {
continue;
}
int left = j + 1;
int right = nums.length - 1;
while (right > left) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum > target) {
right--;
} else if (sum < target) {
left++;
} else {
result.add(Arrays.asList(nums[i], nums[j], 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;
}
}
最折磨的一集,说是哈希表但是大部分时间在捣鼓多指针,去重折磨了我好久