当前位置:网站首页>LeetCode454. Four number addition II
LeetCode454. Four number addition II
2022-04-22 11:41:00 【Want to get into Ali's chicken】
Ideas
Train of thought : Brute force .
Sum arrays in pairs . But it will time out .
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;
}
}
Train of thought two : Using hash table
The hash table can save the repeated results of the sum in two arrays in the hash table , It can reduce the time complexity .
Use the sum of the elements in the first two arrays map Storage ,map Of key Is and , The value is 1, If key Repeat will value++;
0- The sum of the last two arrays is the sum of the first two arrays , That is to say map Of key, Take the corresponding value That's all right. .
Code
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);
}
}
}
// Count the sum of the remaining two elements , stay map Find out if there is an addition to 0 The situation of , Record the number of times at the same time
for (int i : nums3) {
for (int j : nums4) {
int temp = i + j;
if (map.containsKey(0 - temp)) {
res += map.get(0 - temp);
}
}
}
return res;
}
}
版权声明
本文为[Want to get into Ali's chicken]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204221138456978.html
边栏推荐
猜你喜欢

Redis resolves key conflicts

Looking for investors of state-owned enterprises, central enterprises and listed companies, I choose Tami dog!

云中漫步-旅行到宇宙边缘

The new Vemma M7 won two international awards, namely "if design award" and "red dot product design award"

Msfvenom -- MSF component shell generation tool

How to solve this problem when installing MySQL?

塔米狗知识|新三板公司股权转让的流程

云融科技加入龙蜥社区,助力金融行业数字化转型

Basic operation of MySQL

MySQL installation summary
随机推荐
leetcode:347. Top k high frequency elements
L2-030 Icelanders (25 points)
深度迁移学习
12. (map data) cesium city building map
LeetCode454. 四数相加 II
在安装mySQL出现这种问题如何解决呢?
Oracle 手工执行跨平台传输表空间(XTTS)
编写最简单的字符设备驱动
Start with how to read the AWR report
2021-09-17
Oracle manually performs cross platform transfer of tablespaces (xtts)
云中漫步-柴米油盐之上
互联网求职卷中卷,应届生怎样才能杀出重围
LeetCode腾讯精选练习50题-104.二叉树的最大深度
LeetCode202. 快乐数
Chat chat app Lesson 6 creating a main chat static page
将博客搬至CSDN
leetcode:508. 出现次数最多的子树元素和【dfs记录和】
MySQL 学习笔记
2019-8-8-WPF-非客户区的触摸和鼠标点击响应