LeetCode -- 3Sum
生活随笔
收集整理的這篇文章主要介紹了
LeetCode -- 3Sum
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
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系列中,這是最后做的一道,用前面的方法卻錯(cuò)誤多多,很是煩惱。
2sum中,使用了兩種方法,暴力求解(2層for循環(huán))和使用Hashmap的方法;
3sum中,使用2個(gè)指針?lè)謩e指向最大和最小值,同時(shí)要查重,避免重復(fù)的三元組放入list中。
3Sum Closet中,用兩個(gè)變量記錄當(dāng)前sum和sum與target間的差距,而無(wú)需去重檢驗(yàn),總體思路同3Sum。
4sum中,使用兩個(gè)for循環(huán)和2個(gè)指針,分別指向最大和最小的值,然后用HashSet紀(jì)錄選擇過(guò)的四元組。
?
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--;}}}} }?
轉(zhuǎn)載于:https://www.cnblogs.com/little-YTMM/p/4789279.html
總結(jié)
以上是生活随笔為你收集整理的LeetCode -- 3Sum的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: PHPCMS v9 二次开发_验证码结合
- 下一篇: A Complete List of .