LeetCode 18. 4Sum
原题链接在这里:https://leetcode.com/problems/4sum/
题目:
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note: The solution set must not contain duplicate quadruplets.
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0. A solution set is: [ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2] ]
题解:
这道题其实是3Sum的扩展,使用的方法基本相同,只是多加了一层loop.
但要注意一点:For inner j loop, if statement, 判断overflow 时要写成 j>i+1, 而不是j>0, 与 j 的 初始条件有关。若是写成j>0的话,含有四个相同数的输入就会被跳过. e.g. 0,0,0,0 target = 0.
Time Complexity: O(n^3), 两层for, 每一层用时n, 内层for里面的while 用了O(n) time, 一共用了O(n^3).
Space: O(1), regardless res.
AC Java:
1 class Solution { 2 public List<List<Integer>> fourSum(int[] nums, int target) { 3 List<List<Integer>> res = new ArrayList<>(); 4 if(nums == null || nums.length < 4){ 5 return res; 6 } 7 8 Arrays.sort(nums); 9 int n = nums.length; 10 for(int i = 0; i < n - 3; i++){ 11 if(i > 0 && nums[i] == nums[i - 1]){ 12 continue; 13 } 14 15 for(int j = i + 1; j < n - 2; j++){ 16 if(j > i + 1 && nums[j] == nums[j - 1]){ 17 continue; 18 } 19 20 int p = j + 1; 21 int q = n - 1; 22 while(p < q){ 23 long sum = (long)nums[i] + (long)nums[j] + (long)nums[p] + (long)nums[q]; 24 if(sum < (long)target){ 25 p++; 26 }else if(sum > (long)target){ 27 q--; 28 }else{ 29 res.add(Arrays.asList(nums[i], nums[j], nums[p], nums[q])); 30 p++; 31 q--; 32 33 while(p < q && nums[p] == nums[p - 1]){ 34 p++; 35 } 36 37 while(p < q && nums[q] == nums[q + 1]){ 38 q--; 39 } 40 } 41 } 42 } 43 } 44 45 return res; 46 } 47 }
类似4Sum II.
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步