日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Leetcode: 4Sum

發布時間:2025/4/9 编程问答 45 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Leetcode: 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: Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d) 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的思路來做,并以此類推,KSum的復雜度就是O(N^(k-1)). 在3Sum外面再套一層循環,相當于N次求3Sum

若還有時間,可以參考https://discuss.leetcode.com/topic/29585/7ms-java-code-win-over-100

有更多優化

1 public class Solution { 2 public List<List<Integer>> fourSum(int[] num, int target) { 3 List<List<Integer>> res = new ArrayList<List<Integer>>(); 4 if (num==null || num.length==0) return res; 5 Arrays.sort(num); 6 7 int max = num[num.length-1]; 8 if (4 * num[0] > target || 4 * max < target) 9 return res; 10 11 for (int i=num.length-1; i>=3; i--) { 12 if (i<num.length-1 && num[i]==num[i+1]) continue; 13 threeSum(0, i-1, num, target-num[i], res, num[i]); 14 } 15 return res; 16 } 17 18 public void threeSum(int start, int end, int[] num, int target, List<List<Integer>> res, int last1) { 19 for (int i=end; i>=2; i--) { 20 if (i<end && num[i]==num[i+1]) continue; 21 twoSum(0, i-1, num, target-num[i], res, num[i], last1); 22 } 23 } 24 25 public void twoSum(int l, int r, int[] num, int target, List<List<Integer>> res, int last2, int last1) { 26 while (l < r) { 27 if (num[l]+num[r] == target) { 28 List<Integer> set = new ArrayList<Integer>(); 29 set.add(num[l]); 30 set.add(num[r]); 31 set.add(last2); 32 set.add(last1); 33 res.add(new ArrayList<Integer>(set)); 34 l++; 35 r--; 36 while (l<r && num[l] == num[l-1]) { 37 l++; 38 } 39 while (l<r && num[r] == num[r+1]) { 40 r--; 41 } 42 } 43 else if (num[l]+num[r] < target) { 44 l++; 45 } 46 else { 47 r--; 48 } 49 } 50 } 51 }

?

轉載于:https://www.cnblogs.com/EdwardLiu/p/4020087.html

總結

以上是生活随笔為你收集整理的Leetcode: 4Sum的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。