Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

15.三数之和 #41

Open
wind-jyf opened this issue May 7, 2020 · 0 comments
Open

15.三数之和 #41

wind-jyf opened this issue May 7, 2020 · 0 comments
Labels

Comments

@wind-jyf
Copy link
Owner

wind-jyf commented May 7, 2020

三数之和

一、题目详情

给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。

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

示例:

给定数组 nums = [-1, 0, 1, 2, -1, -4]

满足要求的三元组集合为:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

二、解题思路

  1. 设置三个指针,first为nums的每一个数组值,second初始化为first+1,last初始化为数组的最后一个
  2. 先对数组进行排序
  3. 遍历数组,求以first为第一个的所有满足情况
  4. 如果sum<0,则将second++
  5. 如果sum>0,则将last--
  6. 当second和last相遇时,则表示以first为第一个的所有情况已经遍历完毕,此时可以让first++
  7. 重复以上操作直到first达到length-1
  8. 期间有需要去重
  9. first去重、second去重、last去重

三、代码实现

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function(nums) {
    if(!nums || nums.lengt<3){
        return []
    };
    let result = [];//存放结果
    let second;
    let last;
    nums.sort((a,b)=>a-b);//排序
    for(let i=0;i<nums.length;i++){
        if(nums[i]>0){
            break;
        }
        if(i>0 && nums[i] === nums[i-1]){//去重
            continue;
        }
        second = i+1;
        last = nums.length-1;
        while(second<last){
            if(nums[i]+nums[second]+nums[last] == 0){
                result.push([nums[i],nums[second],nums[last]]);
                while(second<last && nums[second] === nums[second+1]){//去重
                    second++;
                }
                while(second<last && nums[last] === nums[last-1]){//去重
                    last--;
                }
                second++;
                last--;
            }else if(nums[i]+nums[second]+nums[last] < 0){
                while(second<last && nums[second] === nums[second+1]){//去重
                    second++;
                }
                second++;
            }else{
                while(second<last && nums[last] === nums[last-1]){//去重
                    last--;
                }
                last--;
            }
            
        }
    }
    return result;
};

@wind-jyf wind-jyf added the 算法 label May 7, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant