leetcode 15. 三数之和

题目描述

代码:

cpp 复制代码
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        int len = nums.size();
        int left = 0;
        int right = 0;
        vector<vector<int>> res;
        for(int i = 0;i <len;i++){
            if(nums[i]>0)
                break;
            if(i>0 && nums[i-1] == nums[i])
                continue;
            left = i+1;
            right = len-1;
            while(left <right){
                if(nums[i]+nums[left]+nums[right] == 0){
                    while(nums[left] == nums[left+1]&&left+1<right)
                        left++;
                    while(nums[right] == nums[right-1]&&left<right-1)
                        right--;
                    res.push_back({nums[i],nums[left],nums[right]});
                    left++;
                    right--;
                }
                else if(nums[i]+nums[left]+nums[right] > 0)
                    right--;
                else
                    left++;
            }
        }
        return res;
    }
};
相关推荐
alphaTao18 小时前
LeetCode 每日一题 2026/7/20-2026/7/26
算法·leetcode
圣保罗的大教堂19 小时前
leetcode 3514. 不同 XOR 三元组的数目 II 中等
leetcode
青山木1 天前
Hot 100 ---腐烂的橘子
java·数据结构·后端·算法·leetcode·广度优先
xqqxqxxq1 天前
LeetCode Hot100 双指针专项题解笔记
笔记·算法·leetcode
闪电悠米1 天前
力扣hot100-54.螺旋矩阵-模拟边界控制详解
算法·leetcode·矩阵
To_OC1 天前
LC 51 N 皇后:我以为难的是回溯,结果栽在了对角线下标
javascript·算法·leetcode
闪电悠米2 天前
力扣hot100-73.矩阵置零-标记数组详解
算法·leetcode·矩阵
过期动态2 天前
【LeetCode 热题 100】找到字符串中所有字母异位词
java·数据结构·算法·leetcode·职场和发展·rabbitmq
Adios7942 天前
设置交集大小至少为2
数据结构·算法·leetcode
程序猿乐锅3 天前
【数据结构与算法 | 第六篇】力扣1109,1094差分数组
java·算法·leetcode