Leecode15. 三数之和——Leecode大厂热题100道系列
生活随笔
收集整理的這篇文章主要介紹了
Leecode15. 三数之和——Leecode大厂热题100道系列
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
我是小張同學,立志用最簡潔的代碼做最高效的表達
以下是我個人做的題解,每個題都盡量囊括了所有解法,并做到了最優(yōu)解,歡迎大家收藏!留言!
傳送門——>Leecode大廠熱題100道系列題解
問題描述
給你一個包含 n 個整數(shù)的數(shù)組 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?請你找出所有和為 0 且不重復的三元組。
注意:答案中不可以包含重復的三元組。
示例 1:
輸入:nums = [-1,0,1,2,-1,-4]
輸出:[[-1,-1,2],[-1,0,1]]
示例 2:
輸入:nums = []
輸出:[]
示例 3:
輸入:nums = [0]
輸出:[]
提示:
0 <= nums.length <= 3000
-105 <= nums[i] <= 105
核心思路
排序 + 雙指針 + 固定消元法
做法
- 當 nums[i]+nums[L]+nums[R]==0nums[i]+nums[L]+nums[R]==0nums[i]+nums[L]+nums[R]==0,執(zhí)行循環(huán),判斷左界和右界是否和下一位置重復,去除重復解。 并同時將 L,RL,RL,R 移到下一位置,尋找新的解
- 若和大于 000,說明 nums[R]nums[R]nums[R] 太大,RRR 左移
- 若和小于 000,說明 nums[L]nums[L]nums[L]太小,LLL 右移
代碼
class Solution { public:vector<vector<int>> threeSum(vector<int>& nums) {vector<vector<int>> res;set<vector<int>> s;sort(nums.begin(), nums.end());for(int i = 0; i < nums.size(); i++) {// 去重if(i > 0 && nums[i] == nums[i-1]) continue;// 如果 > 0 代表后面的都大于0if(nums[i] > 0) break;int l = i + 1, r = nums.size()-1;while(l < r) {int t = nums[i] + nums[l] + nums[r];if(t == 0) {res.push_back({nums[i], nums[l], nums[r]});while(l < r && nums[l] == nums[l+1]) l++;while(l < r && nums[r] == nums[r-1]) r--;r--; l++;} else if(t > 0) {r--;} else if(t < 0) {l++;}}}return res;} };總結(jié)
以上是生活随笔為你收集整理的Leecode15. 三数之和——Leecode大厂热题100道系列的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leecode11. 盛最多水的容器——
- 下一篇: Leecode17. 电话号码的字母组合