题解 | #数组中相加和为0的三元组#

数组中相加和为0的三元组

http://www.nowcoder.com/practice/345e2ed5f81d4017bbb8cc6055b0b711

 * 
 * @param num int整型一维数组 
 * @return int整型二维数组
 */
function threeSum( num ) {
    // write code here
    let len = num.length;
    if(len < 3)    return [];
    num.sort(function(a,b){return a - b});    //    排序
    let res = [];
    let target,left,right,sum;
    for(let i = 0;i < len - 2;i++){
        while(i > 0 && num[i] === num[i - 1])    i++;    //去重
        target = -num[i];
        left = i + 1;
        right = len - 1;
        while(left < right){
            sum = num[left] + num[right];
            if(sum === target){
                res.push([num[i],num[left],num[right]]);
                while(left < right && num[left] === num[left + 1])    left++;    //去重
                left++;
            }else{
                sum > target ? right-- : left++;
            }
        }
    }
    
    return res;
}
module.exports = {
    threeSum : threeSum
};

alt

全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 12:10
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-03 18:22
投了几百份简历,专业和方向完全对口,都已读不回。尝试改了一下学校,果然有奇效。
steelhead:这不是很正常嘛,BOSS好的是即便是你学院本可能都会和聊几句,牛客上学院本机会很少了
点赞 评论 收藏
分享
陆续:不可思议 竟然没那就话 那就我来吧 :你是我在牛客见到的最美的女孩
点赞 评论 收藏
分享
下个早班:秒挂就是不缺人
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务