当前位置:网站首页>LeetCode454. 四数相加 II
LeetCode454. 四数相加 II
2022-04-22 11:39:00 【想进阿里的小菜鸡】
思路
思路一:暴力破解。
将数组两两求和。但是会超时。
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
int[] res1 = sum(nums1,nums2);
int[] res2 = sum(nums3,nums4);
int l1 = res1.length;
int l2 = res2.length;
int res=0;
for(int i =0 ;i<l1;i++){
for(int j = 0;j<l2;j++){
if(res1[i]+res2[j] == 0)
res++;
}
}
return res;
}
public int[] sum(int[] nums1, int[] nums2){
int l1 = nums1.length;
int l2 = nums2.length;
int[] res = new int[l1*l2];
int index = 0;
for(int i =0 ;i<l1;i++){
for(int j = 0;j<l2;j++){
res[index] = nums1[i]+nums2[j];
index++;
}
}
return res;
}
}
思路二:用哈希表
哈希表可以将两个数组中的和的重复出现的结果保存在哈希表中,可以降低时间复杂度。
将前两个数组中元素的和用map存储,map的key是和,值为1,如果key重复出现就将value++;
0-后两个数组的和得到的就是前两个数组的和,也就是map的key,取对应的value就可以了。
代码
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 =0;i<nums1.length;i++){
for(int j =0;j<nums2.length;j++){
int temp = nums1[i]+nums2[j];
if(map.containsKey(temp)){
map.put(temp, map.get(temp) + 1);
}else{
map.put(temp,1);
}
}
}
//统计剩余的两个元素的和,在map中找是否存在相加为0的情况,同时记录次数
for (int i : nums3) {
for (int j : nums4) {
int temp = i + j;
if (map.containsKey(0 - temp)) {
res += map.get(0 - temp);
}
}
}
return res;
}
}
版权声明
本文为[想进阿里的小菜鸡]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_56640241/article/details/124331339
边栏推荐
- 深度报告:异构时代,芯片需集成多个模板
- APISIX jwt-auth 插件存在错误响应中泄露信息的风险公告(CVE-2022-29266)
- mysql-prepare用法
- Summary of seven design principles
- Talent Plan 学习营初体验:交流+坚持 开源协作课程学习的不二路径
- .env. Dev does not take effect
- 怎么得到tuphub.today热榜和热度呢?
- Fundamentals of machine learning
- Yunrong technology joined the dragon dragon dragon community to help the digital transformation of the financial industry
- Redis environment installation
猜你喜欢
随机推荐
Development of digital collection system and construction of digital collection app system
MySQL view database and table creation statements
[security construction] Sysmon, the best tool for log monitoring
进程池创建多进程下载网页
云中漫步-我这一辈子
TS中通过变量存储key值读取对象的属性值时报错(TS: 7053)
Discrete mathematics Chapter 1
Chat chat app Lesson 6 creating a main chat static page
Postman interface testing tool video tutorial, zero basic entry to master graduation
ES6 learning notes 4 numerical representation related to numerical expansion (octal representation) (reprinted, the memo is not my original)
2019-8-8-WPF-非客户区的触摸和鼠标点击响应
Half an hour to understand JSP
uniApp 学习笔记总结(一)
CrashSight 接入上报常见问题及解决方案
深度迁移学习
synchronized实现和原理分析
Intelligent party building integrated management platform development, digital party building integrated management system
redis 登录客户端命令
基于泰凌微TLSR825x的物联网解决方案之ibeacon开发总结
机器学习基础









