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;
    }
};
相关推荐
_日拱一卒12 分钟前
LeetCode:移动零
算法·leetcode·职场和发展
_日拱一卒1 小时前
LeetCode:字母异位词分组
算法·leetcode·职场和发展
Zaly.1 小时前
【Python刷题】LeetCode 3567 子矩阵的最小绝对差
python·leetcode·矩阵
Morwit1 小时前
*【力扣hot100】 215. 数组中的第K个最大元素
数据结构·c++·算法·leetcode·职场和发展
我是咸鱼不闲呀1 小时前
力扣Hot100系列21(Java)——[多维动态规划]总结(不同路径,最小路径和,最长回文子串,最长公共子序列, 编辑距离)
java·leetcode·动态规划
sheeta19981 小时前
LeetCode 每日一题笔记 2025.03.20 3567.子矩阵的最小绝对差
笔记·leetcode·矩阵
旖-旎2 小时前
二分查找(山脉数组的峰顶索引)(5)
c++·算法·leetcode·二分查找·力扣·双指针
阿Y加油吧3 小时前
力扣打卡day06——滑动窗口最大值、最小覆盖子串
数据结构·算法·leetcode
alphaTao4 小时前
LeetCode 每日一题 2026/3/16-2026/3/22
linux·windows·leetcode
空空潍4 小时前
LeetCode力扣 hot100一刷完结
算法·leetcode