1 Star 0 Fork 332

大宇 / leetcode

forked from doocs / leetcode 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
README_EN.md 3.38 KB
一键复制 编辑 原始数据 按行查看 历史

259. 3Sum Smaller

中文文档

Description

Given an array of n integers nums and an integer 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.

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

 

Example 1:

Input: nums = [-2,0,1,3], target = 2
Output: 2
Explanation: Because there are two triplets which sums are less than 2:
[-2,0,1]
[-2,0,3]

Example 2:

Input: nums = [], target = 0
Output: 0

Example 3:

Input: nums = [0], target = 0
Output: 0

 

Constraints:

  • n == nums.length
  • 0 <= n <= 300
  • -100 <= nums[i] <= 100
  • -100 <= target <= 100

Solutions

Python3

class Solution:
    def threeSumSmaller(self, nums: List[int], target: int) -> int:
        def threeSumSmaller(nums, start, end, target):
            count = 0
            while start < end:
                if nums[start] + nums[end] < target:
                    count += (end - start)
                    start += 1
                else:
                    end -= 1
            return count

        nums.sort()
        n, count = len(nums), 0
        for i in range(n - 2):
            count += threeSumSmaller(nums, i + 1, n - 1, target - nums[i])
        return count

Java

class Solution {
    public int threeSumSmaller(int[] nums, int target) {
        Arrays.sort(nums);
        int n = nums.length;
        int count = 0;
        for (int i = 0; i < n - 2; ++i) {
            count += threeSumSmaller(nums, i + 1, n - 1, target - nums[i]);
        }
        return count;
    }

    private int threeSumSmaller(int[] nums, int start, int end, int target) {
        int count = 0;
        while (start < end) {
            if (nums[start] + nums[end] < target) {
                count += (end - start);
                ++start;
            } else {
                --end;
            }
        }
        return count;
    }
}

JavaScript

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var threeSumSmaller = function (nums, target) {
    let len = nums.length;
    if (len < 3) return 0;
    nums.sort((a, b) => a - b)
    let res = 0;
    for (let i = 0; i < len - 2; i++) {
        let left = i + 1, right = len - 1;
        if (nums[i] + nums[left] + nums[i + 2] >= target) break;
        while (left < right) {
            if (nums[i] + nums[left] + nums[right] < target) {
                res += (right - left);
                left++;
                continue;
            } else {
                right--;
                continue;
            }
        }
    }
    return res;
};

...

马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/fdayu/leetcode.git
git@gitee.com:fdayu/leetcode.git
fdayu
leetcode
leetcode
main

搜索帮助

344bd9b3 5694891 D2dac590 5694891