From 06ebd5f204f8a7012c1e4518ce778fa06750d7e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=93=88=E5=93=88=E5=93=88?= <76643786+Projecthappy@users.noreply.github.com> Date: Thu, 23 Mar 2023 00:08:57 +0800 Subject: [PATCH] =?UTF-8?q?Update=200454.=E5=9B=9B=E6=95=B0=E7=9B=B8?= =?UTF-8?q?=E5=8A=A0II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 原先是先判断map中是否有这个key,后面更新时再get(key),经过测试,直接使用getOrDefault()方法效率会更高一些,没有当前key时返回0,值为0就是没有当前key --- problems/0454.四数相加II.md | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/problems/0454.四数相加II.md b/problems/0454.四数相加II.md index c2a5710f..411b60e8 100644 --- a/problems/0454.四数相加II.md +++ b/problems/0454.四数相加II.md @@ -97,26 +97,25 @@ Java: ```Java class Solution { public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) { - Map map = new HashMap<>(); - int temp; int res = 0; + Map map = new HashMap(); //统计两个数组中的元素之和,同时统计出现的次数,放入map for (int i : nums1) { for (int j : nums2) { - temp = i + j; - if (map.containsKey(temp)) { - map.put(temp, map.get(temp) + 1); + int tmp = map.getOrDefault(i + j, 0); + if (tmp == 0) { + map.put(i + j, 1); } else { - map.put(temp, 1); + map.replace(i + j, tmp + 1); } } } //统计剩余的两个元素的和,在map中找是否存在相加为0的情况,同时记录次数 for (int i : nums3) { for (int j : nums4) { - temp = i + j; - if (map.containsKey(0 - temp)) { - res += map.get(0 - temp); + int tmp = map.getOrDefault(0 - i - j, 0); + if (tmp != 0) { + res += tmp; } } }