|
| 1 | +import java.nio.file.attribute.UserPrincipalNotFoundException; |
| 2 | +import java.util.ArrayList; |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +/** |
| 7 | + * LC#15:3Sum |
| 8 | + * Link:https://leetcode-cn.com/problems/3sum/ |
| 9 | + * Solution: |
| 10 | + * 1:Hash:最初的想法将 b 和 c 放入 Hash 中,然后逐渐从 Hash 中取计算 a + b + c = 0,时间复杂度 O(n2),空间复杂度 O(n) |
| 11 | + * 2:Sort + Find:刚开始一直想用 Hash 来解题,因为比较简单直观,但是论坛似乎都在推荐这种做法,确实高效,但是代码也更加复杂。先用排序排一排,找到 a 后,再用双指针在剩下的元素中找 b 和 c,时间复杂度 O(n2),空间复杂度 O(1) |
| 12 | + */ |
| 13 | +public class S15 { |
| 14 | + |
| 15 | + public List<List<Integer>> threeSum(int[] nums) { |
| 16 | + int n = nums.length; |
| 17 | + Arrays.sort(nums); |
| 18 | + |
| 19 | + List<List<Integer>> ans = new ArrayList<>(); |
| 20 | + // 枚举 a |
| 21 | + for (int first = 0; first < n; first++) { |
| 22 | + // 跳过相同的值 |
| 23 | + if (first > 0 && nums[first] == nums[first - 1]) { |
| 24 | + continue; |
| 25 | + } |
| 26 | + int third = n - 1; |
| 27 | + int target = -nums[first]; |
| 28 | + // 枚举 b |
| 29 | + for (int second = first + 1; second < n; second++) { |
| 30 | + // 跳过相同的值 |
| 31 | + if (second > first + 1 && nums[second] == nums[second - 1]) { |
| 32 | + continue; |
| 33 | + } |
| 34 | + while (second < third && nums[second] + nums[third] > target) { |
| 35 | + --third; |
| 36 | + } |
| 37 | + // 不可能有结果,退出循环 |
| 38 | + if (second == third) { |
| 39 | + break; |
| 40 | + } |
| 41 | + |
| 42 | + if (nums[second] + nums[third] == target) { |
| 43 | + List<Integer> list = new ArrayList<>(); |
| 44 | + list.add(nums[first]); |
| 45 | + list.add(nums[second]); |
| 46 | + list.add(nums[third]); |
| 47 | + ans.add(list); |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + return ans; |
| 52 | + } |
| 53 | + |
| 54 | + public static void main(String[] args) { |
| 55 | + int[] nums = {-1, 0, 1, 2, -1, -4}; |
| 56 | + List<List<Integer>> list = new S15().threeSum(nums); |
| 57 | + System.out.println(list); |
| 58 | + } |
| 59 | +} |
0 commit comments