首页 > 其他分享 >双指针妙解三数之和

双指针妙解三数之和

时间:2024-03-31 22:33:51浏览次数:18  
标签:sortedNums right nums 三数 妙解 let triplets left 指针

三数之和算是名气很大的算法题,我今天刚好刷到,用JavaScript实现了一下。
题目如下所示:

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

 

Example 1:

Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation: 
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The distinct triplets are [-1,0,1] and [-1,-1,2].
Notice that the order of the output and the order of the triplets does not matter.
Example 2:

Input: nums = [0,1,1]
Output: []
Explanation: The only possible triplet does not sum up to 0.
Example 3:

Input: nums = [0,0,0]
Output: [[0,0,0]]
Explanation: The only possible triplet sums up to 0.
 

Constraints:

3 <= nums.length <= 3000
-105 <= nums[i] <= 105

相比之前一道两数之和,三数之和的难度增加了一些,变量变成了3个,并且不止一个解。如果还是用暴力破解的算法就需要3个嵌套循环,这样算法的时间复杂度就是n^3,是非常差的算法。
这里可以思考把第一个数当成一个固定的数,通过遍历的方式逐一尝试,这样就可以变回我们熟悉的两数之和的套路了。通过两个指针,不断推移,当3个数加起来等0的时候,把当前三个数加到结果的数组里面,然后继续寻找下一个解。其中要注意处理重复的值,当有重复项出现,就移动指针到下一个,减少重复对比,提高效率。

具体实现如下所示:


/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function(nums) {
    // Sort the array named nums
    const sortedNums = nums.sort((a, b) => a - b);

    const result = [];

    for (let i = 0; i < sortedNums.length - 2; i++) {
        // Skip the duplicated item
        if (i > 0 && sortedNums[i] === sortedNums[i - 1]) continue;

        let left = i + 1;
        let right = sortedNums.length  - 1;

        while(left < right) {
            let total = sortedNums[i] + sortedNums[left] + sortedNums[right];

            if (total === 0) {
                result.push([sortedNums[i], sortedNums[left], sortedNums[right]]);
                // Handle the duplicated item
                while(left < right && sortedNums[left] === sortedNums[left + 1]) {
                    left += 1;
                }

                while(left < right && sortedNums[right] === sortedNums[right - 1]) {
                    right -= 1;
                }
                // Move to the next unique item
                left += 1;
                right -= 1;
            } else if (total < 0) {
                left += 1;

            } else {
                right -= 1;
            }
        }

    }
    return result;
};

想不明白的时候可以画图去看看指针移动的过程,好头脑也不如画个图。留下一个问题,那如果是四数之和呢,又怎么解决呢?

标签:sortedNums,right,nums,三数,妙解,let,triplets,left,指针
From: https://www.cnblogs.com/freephp/p/18107403

相关文章

  • 内联函数 auto 基于范围for循环 空指针nullptr
    内联函数(C98)1.含义以inline修饰的函数叫做内联函数,编译时C++编译器会在调用内联函数的地方展开,没有函数压栈的开销,内联函数提升程序运行的效率。(官方术语)C++内联函数和C语言的宏函数很像,都是在编译时调用的地方展开,函数调用要开辟空间消耗栈要花蛮多时间,而内联函数不要开辟......
  • #include<初见C语言之指针(5)>
    目录一、sizeof和strlen的对比1. sizeof2.strlen二、数组和指针题解析1.⼀维数组1.1数组名理解2.字符数组 3. ⼆维数组三、指针运算题解析总结一、sizeof和strlen的对比1. sizeof我们前面介绍过sizeof是单目操作符sizeof括号中有表达式,不计算 计算变......
  • PTA (指针和数组 )R7-2 在数组中查找指定元素
    R7-2在数组中查找指定元素分数10入门全屏浏览切换布局作者 王秀单位 福州大学输入一个正整数repeat(0<repeat<10),做repeat次下列运算:输入一个正整数n(1<n<=10),然后输入n个整数存入数组a中,再输入一个整数x,在数组a中查找x,如果找到则输出相应元素的最小下标,否则......
  • C++类(class)中的this指针与静态成员
    1.this指针作用:指向成员函数所作用的对象2.静态成员定义方式:在定义成员时加static关键字。访问方式:不用通过对象就可以访问(类似全局变量/全局函数)目的:设置静态成员这种机制的目的是将和某些类紧密相关的全局变量和函数写到类里面,看上去像一个整体,易于维护和理解。①......
  • Pointer-like classes像指针又像函数
    Pointer-likeclasses像指针又像函数智能指针概念:一个类做出来像类又像指针示例代码:#pragmaonce#ifndef__SHAREPOINTER__#define__SHAREPOINTER__​template<classT>classshared_ptr{public:shared_ptr(T*p):px(p){}T&operator*()const{return*px;}......
  • C语言入门:数组与指针的关系
    目录深入理解指针操作指针的基本概念指针与数组的关系指针与函数动态内存分配与释放内存分配函数内存释放函数动态内存管理注意事项深入理解指针操作、动态内存分配与释放是C语言编程中的核心技能。以下内容将进一步详细阐述这些主题,旨在帮助开发者更好地掌握指针......
  • C语言: 指针讲解
    为什么需要指针?(1)指针的使用使得不同区域的代码可以轻易的共享内存数据。当然你也可以通过数据的复制达到相同的效果,但是这样往往效率不太好,因为诸如结构体等大型数据,占用的字节数多,复制很消耗性能。但使用指针就可以很好的避免这个问题,因为任何类型的指针占用的字节数都是一......
  • C语言复习 -- 指针,这篇够了
    指针 -- 地址指针就是地址,地址就是指针&--取地址运算符*取值运算符(解引用)得到地址--要访问他的值--*取值运算符-- 对地址解引用a=*(&a)----------------------------指针变量 --存放指针的变量 初始化方式--int*p;inta=10;   in......
  • 用函数指针数组来实现对一系列函数的调用
    include<stdio.h>intadd(inta,intb);intsub(inta,intb);intmax(inta,intb);intmin(inta,intb);voidmain(){inta,b,i,k;int(*func[4])(int,int)={add,sub,max,min}//定义指针数组,并对其赋初始值printf("selectoperator(0-add,1-sub,2-max,3-min)......
  • 实验报告( 重载,引用,指针,交换,字符串的连接 )
       一、实验目的:掌握函数重载的使用方法深入理解指针的概念,掌握指针的使用方法理解引用的概念,掌握引用作为函数参数的使用方法二、实验仪器或设备:微型计算机三、总体设计(设计原理、设计方案及流程等)实验内容:1、设计一组重载函数add(),至少包括:charadd(char,int);......