454. 四数相加I
题目链接:454. 四数相加II
思路: 先创建一个hashmap,使用两个for循环将前两个数组中的各项和作为key,和的个数作为value,存入map。然后再使用两个for循环求后两个数组的各项和的相反数,在map中去找这个相反数。
我的代码:
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
// 用map存储 nums1和nums2各项和
HashMap<Integer, Integer> map1 = new HashMap<>();
int n = nums1.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int sum1 = nums1[i] + nums2[j];
map1.put(sum1, map1.getOrDefault(sum1, 0) + 1);
}
}
int res = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j< n; j++) {
int sum2 = nums3[i] + nums4[j];
int target = -sum2;
if (map1.containsKey(target)) {
res += map1.get(target);
}
}
}
return res;
}
}
问题:
总结:
383. 赎金信
题目链接:383. 赎金信
思路: magazine作为字典,创建一个长度为26的数组,将magazine中的每个char - ‘a',数组中对应的索引的值++,接下来对ransomNote中的每一个char,对数组中相应的char - ’a'索引--。检查数组中的每一个数字,如果 <0 返回false。
我的代码:
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
// magaine作为字典
int[] dic = new int[26];
for (char c : magazine.toCharArray()) {
dic[c - 'a']++;
}
for (char c : ransomNote.toCharArray()) {
dic[c - 'a']--;
}
for (int i : dic) {
if (i < 0) return false;
}
return true;
}
}
问题:
总结:
15. 三数之和
题目链接:15. 三数之和
思路: 刚开始很自然地想着用哈希表做,但是想了想感觉去重会非常麻烦
我的代码:
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new LinkedList<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
if (nums[i] > 0) {
return res;
}
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int left = i + 1;
int right = nums.length - 1;
while (right > left) {
int sum = nums[i] + nums[left] + nums[right];
if (sum > 0) {
right--;
} else if (sum < 0) {
left++;
} else {
res.add(Arrays.asList(nums[i], 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 res;
}
}
问题:
总结:
使用双指针的方法将原本暴力O(n^3)的解法,降为O(n^2)的解法。注意剪枝操作。
18. 四数之和
题目链接:18. 四数之和
思路: 有了三数之和的经验,四数之和就是在三数之和的基础上多一个循环。
我的代码:
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new LinkedList<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length - 3; i++) {
// 剪枝操作
if (nums[i] > 0 && nums[i] > target) return res;
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 left = j + 1;
int right = nums.length - 1;
while (right > left) {
long sum = (long) nums[i] + nums[j] + nums[left] + nums[right];
if (sum > target) {
right--;
} else if (sum < target) {
left++;
} else {
res.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++;
right--;
left++;
}
}
}
}
return res;
}
}
问题:
总结:
剪枝操作的细节有点多。