学习目标:
- 454.四数相加II
- 383. 赎金信
- 15. 三数之和
- 18. 四数之和
解题记录:
454.四数相加II
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
Map<Integer, Integer> map = new HashMap<>();
int count = 0;
//统计两个数组中的元素之和,同时统计出现的次数,放入map
for(int i = 0; i < nums1.length; i++) {
for(int j = 0; j < nums2.length; j++){
int temp = nums1[i] + nums2[j];
if(!map.containsKey(nums1[i] + nums2[j])){
map.put(temp, 1);
}else{
map.put(temp, map.get(temp) + 1);
}
}
}
//统计剩余的两个元素的和,在map中找是否存在相加为0的情况,同时记录次数
for(int m = 0; m < nums3.length; m++) {
for(int n = 0; n <nums4.length; n++) {
int temp = 0 - (nums3[m] + nums4[n]);
if(map.containsKey(temp)) {
count += map.get(temp);//注意加的是value值
}
}
}
return count;
}
}
383. 赎金信
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
// 定义一个哈希映射数组
int[] record = new int[26];
// 遍历
for(char c : magazine.toCharArray()) {
record[c - 'a']++;
}
for(char c : ransomNote.toCharArray()) {
record[c - 'a']--;
}
// 如果数组中存在负数,说明ransomNote字符串总存在magazine中没有的字符
for(int i : record) {
if(i < 0) {
return false;
}
}
return true;
}
}
15. 三数之和
先排序再用双指针
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
//创建集合存储对应结果集
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);// 首先对nums进行排序
for(int i = 0; i < nums.length; i++) {
// 排序后如果第一个元素大于零,那么无论如何都不可能凑成三元组,直接返回结果
if(nums[0] > 0) {
return result;
}
if(i > 0 && nums[i] == nums[i-1]) { // a去重
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--;
}
if(sum < 0){
left++;
}
if(sum == 0){
result.add(Arrays.asList(nums[i], nums[left], nums[right]));
// 去重逻辑应该放在找到一个三元组之后,对b 和 c去重
while(right > left && nums[left] == nums[left+1]) left++;
while(right > left && nums[right] == nums[right-1]) right--;
// 找到答案时,双指针同时收缩
left++;
right--;
}
}
}
return result;
}
}
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++) {
// nums[i] > target 直接返回, 剪枝操作
if(nums[i] > target && nums[i] > 0) {
return result;
}
if( i > 0 && nums[i] == nums[i-1]) {// a去重
continue;
}
for(int j = i + 1; j < nums.length - 2; j++) {
//while(j > i + 1 && nums[j] == nums[j-1]) j++;//b去重,这样写不通过
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];//转成long,四个int相加有可能溢出
if(sum > target) {
right--;
}else if(sum < target) {
left++;
}else {
result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
//c、d去重
while(right > left && nums[left] == nums[left+1]) left++;
while(right > left && nums[right] == nums[right-1]) right--;
// 找到答案时,双指针同时收缩
left++;
right--;
}
}
}
}
return result;
}
}
学习成果:
- 454.四数相加II
- 383. 赎金信
- 15. 三数之和
- 18. 四数之和