代码随想录第七天 | 454.四数相加II , 383. 赎金信 , 15. 三数之和,18. 四数之和
今天是第七天 内容依旧是HashMap相关
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 : nums1){ for(int j : nums2){ int temp = i + j; map.put(temp, map.getOrDefault(temp,0)+1); } } for(int i:nums3){ for(int j : nums4){ int temp = -i - j; if(map.containsKey(temp)){ res += map.get(temp); } } } return res; } }
创建一个hashmap,记录前两个array中的和,再一一对比后面的两个array中,是否有两组数组加起来正好等于前两个array中每两个元素和的负数,如果有的话,就让res加上这些数字出现的次数。
class Solution { public boolean canConstruct(String ransomNote, String magazine) { Map<Character, Integer> map = new HashMap<>(); int n = magazine.length(); int m = ransomNote.length(); for(int i = 0; i<n; i++){ map.put(magazine.charAt(i), map.getOrDefault(magazine.charAt(i), 0)+1); } for(int i = 0; i<m; i++){ if(!map.containsKey(ransomNote.charAt(i))||map.get(ransomNote.charAt(i))<=0){ return false; } else{ map.put(ransomNote.charAt(i),map.get(ransomNote.charAt(i))-1); } } return true; } }
把杂志的字母记录进hashmap,看看letter的字符是否在hashmap中有足够的数量
class Solution { public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); int n = nums.length; List<List<Integer>> res = new ArrayList<>(); for(int i = 0; i<n -2; i++){ int l = i + 1; int r = n -1; while(l<r){ int sum=nums[l]+nums[r]+nums[i]; if(sum<0){ l++; }else if(sum==0){ res.add(Arrays.asList(nums[i],nums[l],nums[r])); int lv=nums[l],rv=nums[r]; while(l<r&&nums[l]==lv){ l++; } while(l<r&&nums[r]==rv){ r--; } }else{ r--; } } int val=nums[i]; while(val==nums[i]&&i<nums.length-2){ i++; } i--; } return res; } }
背题解,一道很噩梦的题,双指针
class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> result = new ArrayList<>(); if(target == -294967296){ return result; } Arrays.sort(nums); for (int i = 0; i < nums.length; i++) { 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; } }
int溢出了,直接ctrl v题解了,什么破测试用例
然后发现题解也没考虑int 溢出,加了两行,直接面向测试用例编程了
好的,今天是双指针和哈希表混合,最后两道题很重要,一定要会,后面还有更加死亡的n数之和
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?