From 93cbd6955ca70ceddcc55026b55cf991db00bd81 Mon Sep 17 00:00:00 2001 From: whai Date: Wed, 3 Jan 2024 22:13:32 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=89=E6=8C=87=E9=92=88=E8=A7=A3=E5=86=B3ha?= =?UTF-8?q?shmap=E9=97=AE=E9=A2=98=20-=20=E6=B3=A8=E6=84=8F=E9=87=8D?= =?UTF-8?q?=E5=A4=8D=E6=8C=87=E9=92=88=E8=B7=B3=E8=BF=87=E7=9A=84=E6=96=B9?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cn/whaifree/leetCode/Hash/LeetCode15.java | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 src/main/java/cn/whaifree/leetCode/Hash/LeetCode15.java diff --git a/src/main/java/cn/whaifree/leetCode/Hash/LeetCode15.java b/src/main/java/cn/whaifree/leetCode/Hash/LeetCode15.java new file mode 100644 index 0000000..2539acf --- /dev/null +++ b/src/main/java/cn/whaifree/leetCode/Hash/LeetCode15.java @@ -0,0 +1,68 @@ +package cn.whaifree.leetCode.Hash; + +import org.junit.Test; + +import java.util.*; +import java.util.function.Consumer; + +public class LeetCode15 { + + @Test + public void test() { + new Solution().threeSum(new int[]{-1, 0, 1, 2, -1, -4}).forEach(integers -> { + System.out.println(); + integers.forEach( + integer -> System.out.print(integer + " ") + ); + }); + } + + class Solution { + /** + * TODO 2024-1-3 用三指针,没做出来 + * @param nums + * @return + */ + public List> threeSum(int[] nums) { + Arrays.sort(nums); + List> o = new ArrayList<>(); + // 排序后第一个就大于0,必然不可能有结果 + if (nums[0] > 0) { + return o; + } + for (int i = 0; i < nums.length; i++) { + + int left = i + 1; + int right = nums.length - 1; + + // 如果前后两个i 相同,跳过 + if (i > 0 && nums[i] == nums[i - 1]) { // 去重a + continue; + } + + while (left < right) { + int number = nums[i] + nums[right] + nums[left]; + if (number > 0) { + right--; + } else if (number < 0) { + left++; + } else { + o.add(Arrays.asList(nums[i], nums[left], nums[right])); + // 去重逻辑应该放在找到一个三元组之后,对b 和 c去重 + // 如果 right左边的两个一样,去重,跳过去,但依然要保证要比left大 + while (right > left && nums[right] == nums[right - 1]){ + right--; + } + while (right > left && nums[left] == nums[left + 1]) { + left++; + } + right--; + left++; + } + } + + } + return o; + } + } +}