leetcode15 三数之和
生活随笔
收集整理的這篇文章主要介紹了
leetcode15 三数之和
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
給定一個包含 n 個整數(shù)的數(shù)組?nums,判斷?nums?中是否存在三個元素 a,b,c ,使得?a + b + c = 0 ?找出所有滿足條件且不重復(fù)的三元組。
注意:答案中不可以包含重復(fù)的三元組。
例如, 給定數(shù)組 nums = [-1, 0, 1, 2, -1, -4],
滿足要求的三元組集合為:
[
? [-1, 0, 1],
? [-1, -1, 2]
]
思路:枚舉最左邊的數(shù),對另外兩個數(shù)雙指針查詢。
注意:去除重復(fù)
class Solution {public List<List<Integer>> threeSum(int[] nums) {List<List<Integer>> listArr=new ArrayList<>();int len=nums.length;int left,right;Arrays.sort(nums);for(int i=0;i<len;++i){if(i>0 && nums[i] == nums[i-1]) continue;//去重left=i+1;right=len-1;while(left<right) {int three=nums[left]+nums[right]+nums[i];if(three>0){++right;}else if(three<0){++left;}else{listArr.add(Arrays.asList(nums[i],nums[left],nums[right]));while(left<right && nums[left]==nums[left+1])left++;//去重while(left<right && nums[right]==nums[right-1])right--;//去重++left;--right;}}}return listArr;} }?
?
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的leetcode15 三数之和的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode344. 反转字符串 史
- 下一篇: 数据结构课上笔记11