From fa02907e888d741b07fc057c78a065070cf09963 Mon Sep 17 00:00:00 2001 From: Powerstot <77142630+Powerstot@users.noreply.github.com> Date: Wed, 12 May 2021 10:59:24 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00018.=E5=9B=9B=E6=95=B0?= =?UTF-8?q?=E4=B9=8B=E5=92=8C=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加0018.四数之和 Java版本 --- problems/0018.四数之和.md | 41 +++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md index 72f8cee5..ff441bf7 100644 --- a/problems/0018.四数之和.md +++ b/problems/0018.四数之和.md @@ -121,7 +121,48 @@ public: Java: +```Java +class Solution { + public List> fourSum(int[] nums, int target) { + List> result = new ArrayList<>(); + 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; + } +} +``` Python: