[leetcode] 259. 3Sum Smaller 解题报告

题目链接: https://leetcode.com/problems/3sum-smaller/

Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.

For example, given nums = [-2, 0, 1, 3], and target = 2.

Return 2. Because there are two triplets which sums are less than 2:

[-2, 0, 1]
[-2, 0, 3]

Follow up:
Could you solve it in O(n2) runtime?


思路:首先对数组进行排序. 然后同样是先确定一位, 然后双指针一个在最左边, 一个在最右边. 如果三个数的和小于target, 那么在右指针之前的左指针之后的数肯定也是可以的. 注意到这个之后就可以很容易得到答案. 时间复杂度O(N^2).

代码如下:

class Solution {
public:
    int threeSumSmaller(vector<int>& nums, int target) {
        int cnt = 0, len = nums.size();
        sort(nums.begin(), nums.end());
        for(int i = 0; i< len-2; i++)
        {
            int left = i+1, right = len -1;
            while(left < right)
            {
                int val = nums[i]+nums[left]+nums[right];
                if(val < target)
                {
                    cnt+= (right-left);
                    left++;
                }
                else right--;
            }
        }
        return cnt;
    }
};


你可能感兴趣的:(LeetCode,array)