LeetCode Hot100 15.三数之和

题目描述

给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != ji != kj != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请你返回所有和为 0 且不重复的三元组。

**注意:**答案中不可以包含重复的三元组。

15. 三数之和 - 力扣(LeetCode)

思路

首先对nums排序,每次先固定一个numsi,然后在i后面的部分使用双指针l和r进行搜索,如果numsi+numsl+numsr<0,那么l右移,否则r左移

需要保证i,l,r都被去重过,所以在每次迭代一个新的i时,跟之前处理过的numsi-1对比,如果相等那么跳过此次迭代;每次找到一个满足条件的i,l,r时,对l和r去重,跟还未处理过的numsl+1,numsr-1对比,相同则跳过。

代码

html 复制代码
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        Arrays.sort(nums);
        for(int i = 0; i < nums.length-2; i++){
            if(i>0&&nums[i]==nums[i-1]) continue;
            int l=i+1,r=nums.length-1;
            while(l<r){
                if(nums[l]+nums[r]==-nums[i]){
                    ans.add(List.of(nums[l],nums[r],nums[i]));
                    while(l<r&&nums[l]==nums[l+1]) l++;
                    while(l<r&&nums[r]==nums[r-1]) r--;
                    l++;
                    r--;
                }
                else if(nums[l]+nums[r]<-nums[i]){
                    l++;
                }
                else{
                    r--;
                }
            }
        }
        return ans;
    }
}
相关推荐
学究天人11 分钟前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(卷2)
算法·数学建模·动态规划·图论·抽象代数·拓扑学
玛卡巴卡ldf1 小时前
【LeetCode 手撕算法】(细节知识点总结)
java·数据结构·算法·leetcode·力扣
wanzehongsheng1 小时前
零碳产业园光伏园区光伏电站追踪对比固定:发电增益技术边界分析
算法·光伏发电·光伏·零碳园区·太阳能追光·低碳环保·追踪电站
KobeSacre2 小时前
CyclicBarrier 源码
java·jvm·算法
手写码匠2 小时前
注意力机制全家桶:从 Multi-Head 到 GQA 再到 Flash Attention 的手写实现
人工智能·深度学习·算法·aigc
学究天人2 小时前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(卷3.2)
线性代数·算法·机器学习·数学建模·动态规划·抽象代数·拓扑学
tkevinjd3 小时前
力扣322-零钱兑换
算法·leetcode·动态规划
大鱼>3 小时前
AI+资产监控:农业设施智能监控系统
人工智能·深度学习·算法·机器学习
AI科技星3 小时前
乖乖数学·全域超复数统一场论:五大核心门槛与全套标准定量数据
人工智能·python·算法·金融·全域数学
Frostnova丶3 小时前
(13)LeetCode 53. 最大子数组和
算法·leetcode·职场和发展