leetcode 15.3sum 题解

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

题目大意:
给一个数组,求数组里三个数相加和为0的所有情况。

解题思路:
双指针(并不是C中的指针,是指索引,下标)。
双指针具体思路是:初始化两个指针,一个指向数组的第一个元素,另外一个指向数组的最后一个元素,在两个指针相遇之前,指针1只能向前移动,指针2 只能向后移动。比较当前两个指针所指元素和与给定数字的大小,如果和较大,指针2向后移动,如果和较小,指针1向前移动。最终的结果是找到两个满足条件的数或者不存在这样的两个数字。
注意:本题需要剔除相同的情况,比如有两个[-1,0,1]满足,只保留其中一个。

代码如下:

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> ans;
        int l, j, k, n, sum;
        sort(nums.begin(), nums.end());
        n = nums.size();
        l = 0;
        while (l < n-2) {
            if (l != 0 && (nums[l] > 0 || nums[l] == nums[l-1])){
                l++; continue;
            }
            j = l+1; k = n-1;
            while (j < k) {
                sum = nums[j] + nums[k] + nums[l];
                if ( sum== 0)
                    ans.push_back({nums[l], nums[j], nums[k]});
                if (sum < 0) {
                    j++;
                    while((nums[j] == nums[j-1]) && j < k)
                        j++;
                }
                if (sum >= 0) {
                    k--;
                    while((nums[k] == nums[k+1]) && j < k)
                        k--;
                }
            }
            l++;
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/xiaomimi1993/article/details/81486954