美文网首页
leetcode_16最接近的三数之和

leetcode_16最接近的三数之和

作者: 看到这朵小fa了么 | 来源:发表于2020-06-24 10:25 被阅读0次

思路:通过一次遍历,对每个元素,再进行双指针遍历查找,当三数之和小则左指针右移,大则右指针左移,否则直接返回

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var threeSumClosest = function(nums, target) {
    
    let list = nums.sort((a,b)=>a-b)
    let result = list[0]+list[1]+list[2]
    for(let i=0; i<list.length; i++){
        let end = list.length-1
        let start = i+1
        let focus = list[i]
        while(start<end){
            let sum = focus+list[end]+list[start]
            if(Math.abs(sum-target) < Math.abs(result-target)){
               result = sum
            }
            if(sum>target) {
                end--
            } else if(sum<target){
                start++
            } else {
                return result
            }
        }
    }
    return result
};

相关文章

  • leetcode_16最接近的三数之和

    思路:通过一次遍历,对每个元素,再进行双指针遍历查找,当三数之和小则左指针右移,大则右指针左移,否则直接返回

  • algrithrom

    求和问题,双指针解决 done 两数之和 三数之和 最接近三数之和 四数之和 链表反转问题 done 链表反转 链...

  • LeetCode-16 最接近的三数之和

    题目:16. 最接近的三数之和 难度:中等 分类:数组 解决方案:双指针 今天我们学习第16题最接近的三数之和,这...

  • 双指针总结

    左右指针 主要解决数组中的问题:如二分查找 盛最多水的容器 三数之和 四数之和 最接近三数之和 快慢指针 主要解决...

  • LeetCode练习day1-数组相关

    LeetCode16 最接近的三数之和 相似题目:LeetCode15 三数之和 题目详情 给你一个长度为 n 的...

  • 最接近的三数之和

    题目来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/3sum...

  • 最接近的三数之和

    题目 思路 题解

  • 最接近的三数之和

    题目地址 1.思路 第一步很容易想到的就是降维处理,三个数相当于三维,那么我确定一个数的时候只剩下2维,这样就把问...

  • 最接近的三数之和

    leetcode 16 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中...

  • 最接近的三数之和

    来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/3sum-c...

网友评论

      本文标题:leetcode_16最接近的三数之和

      本文链接:https://www.haomeiwen.com/subject/tltrfktx.html