Leetcode 15. 3Sum

文章作者:Tyan
博客:noahsnail.com  |  CSDN  | 

1. Description

Leetcode 15. 3Sum_第1张图片
3Sum

2. Solution

class Solution {
public:
    vector> threeSum(vector& nums) {
        sort(nums.begin(), nums.end());
        vector> result;
        int length = nums.size();
        for(int i = 0; i < length - 1; i++) {
            if(i != 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int target = 0 - nums[i];
            int left = i + 1;
            int right = length - 1;
            while(left < right) {
                if(left != i + 1 && nums[left] == nums[left - 1]) {
                    left++;
                    continue;
                }
                if(right != length - 1 && nums[right] == nums[right + 1]) {
                    right--;
                    continue;
                }
                int sum = nums[left] + nums[right];
                if(sum == target) {
                    vector temp;
                    temp.push_back(nums[i]);
                    temp.push_back(nums[left]);
                    temp.push_back(nums[right]);
                    result.push_back(temp);
                    left++;
                    right--;
                }
                else if(sum < target) {
                    left++;
                }
                else {
                    right--;
                }
            }
        }
        return result;
    }
};

Reference

  1. https://leetcode.com/problems/3sum/description/

你可能感兴趣的:(Leetcode 15. 3Sum)