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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

LeetCode -- 3Sum

發布時間:2025/4/14 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode -- 3Sum 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Question:

Given an array?S?of?n?integers, are there elements?a,?b,?c?in?S?such that?a?+?b?+?c?= 0? Find all unique triplets in the array which gives the sum of zero.

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie,?a?≤?b?≤?c)
  • The solution set must not contain duplicate triplets.

?

For example, given array S = {-1 0 1 2 -1 -4},A solution set is:(-1, 0, 1)(-1, -1, 2)

?

Analysis:

在sum系列中,這是最后做的一道,用前面的方法卻錯誤多多,很是煩惱。

2sum中,使用了兩種方法,暴力求解(2層for循環)和使用Hashmap的方法;

3sum中,使用2個指針分別指向最大和最小值,同時要查重,避免重復的三元組放入list中。

3Sum Closet中,用兩個變量記錄當前sum和sum與target間的差距,而無需去重檢驗,總體思路同3Sum。

4sum中,使用兩個for循環和2個指針,分別指向最大和最小的值,然后用HashSet紀錄選擇過的四元組。

?

Answer:

public class Solution {private List<List<Integer>> res;public List<List<Integer>> threeSum(int[] nums) {res = new ArrayList<List<Integer>> ();Arrays.sort(nums);for(int i=0; i<=nums.length-3; i++) {if(i!=0 && nums[i] == nums[i-1])continue;deal(nums, i, i+1, nums.length-1);}return res;}public void deal(int[] nums, int i, int p, int q) {while(p<q) {if(nums[p] + nums[q] + nums[i] > 0) {q--;}else if(nums[p] + nums[q] + nums[i] < 0) {p++;}else {List<Integer> li = new ArrayList<Integer> ();li.add(nums[i]);li.add(nums[p]);li.add(nums[q]);res.add(li);p++;q--;while(p<q && nums[p]==nums[p-1]) {p++;}while(p<q && nums[q]== nums[q+1]) {q--;}}}} }

?

轉載于:https://www.cnblogs.com/little-YTMM/p/4789279.html

總結

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

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