454. 四数相加 II (学会了,二刷的我,应该也会)
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
// Map< num1+num2 , 出现的次数 >
Map<Integer, Integer> map1 = new HashMap<>();
int tmp;
for (int num1 : nums1) {
for (int num2 : nums2) {
tmp = num1 + num2;
if (!map1.containsKey(tmp)) {
map1.put(tmp, 1);
} else {
map1.put(tmp, map1.get(tmp) + 1);
}
}
}
int count = 0;
for (int num3 : nums3) {
for (int num4 : nums4) {
if (map1.containsKey(-(num3 + num4))) {
count += map1.get(-(num3 + num4));
}
}
}
return count;
}
}
383. 赎金信 (ez)
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] count = new int[26];
char ch;
for (int i = 0; i < magazine.length(); i++) {
ch = magazine.charAt(i);
count[ch - 'a'] += 1;
}
for (int i = 0; i < ransomNote.length(); i++) {
ch = ransomNote.charAt(i);
int tmp = count[ch - 'a'] - 1;
if (tmp < 0) {
return false;
}
count[ch - 'a'] = tmp;
}
return true;
}
}
下面这两个浓眉大眼的 学...会了吗?
15. 三数之和 (学...会了吧!)
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> answer = new ArrayList<>();
List<Integer> tmp = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
if (nums[i] > 0) {
return answer;
}
if (i > 0 && nums[i] == nums[i - 1]) { // 去重a
continue;
}
int right = nums.length - 1, left = i + 1;
while (right > left) {
int sum = nums[i] + nums[left] + nums[right];
if (sum > 0) {
right--;
} else if (sum < 0) {
left++;
} else {
answer.add(Arrays.asList(nums[i], nums[left], nums[right]));
while (right > left && nums[right - 1] == nums[right]) right--;
while (right > left && nums[left + 1] == nums[left]) left++;
right--;
left++;
}
}
}
return answer;
}
}
18. 四数之和 (学...会了吗?)
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> answer = new ArrayList<>();
Arrays.sort(nums);
for (int k = 0; k < nums.length; k++) {
if (nums[k] > target && nums[k] > 0) {
return answer;
}
if (k > 0 && nums[k] == nums[k - 1]) { // 去重k
continue;
}
for (int i = k + 1; i < nums.length; i++) {
if (i > k + 1 && nums[i - 1] == nums[i]) {
continue;
}
int right = nums.length - 1, left = i + 1;
while (right > left) {
long sum = nums[k] + nums[i] + nums[left] + nums[right];
if (sum > target) {
right--;
} else if (sum < target) {
left++;
} else {
answer.add(Arrays.asList(nums[k], nums[i], nums[left], nums[right]));
while (right > left && nums[right] == nums[right - 1]) right--;
while (right > left && nums[left] == nums[left + 1]) left++;
right--;
left++;
}
}
}
}
return answer;
}
}
标签:tmp,right,nums,int,学会,相信,++,二刷,left
From: https://www.cnblogs.com/Chain-Tian/p/16939925.html