资讯专栏INFORMATION COLUMN

[LintCode] 3Sum Smaller

AprilJ / 1008人阅读

Problem

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.

Example

Given nums = [-2,0,1,3], target = 2, return 2.

Explanation:

Because there are two triplets which sums are less than 2:
[-2, 0, 1]
[-2, 0, 3]

Challenge

Could you solve it in O(n2) runtime?

Solution
public class Solution {
    /**
     * @param nums:  an array of n integers
     * @param target: a target
     * @return: the number of index triplets satisfy the condition nums[i] + nums[j] + nums[k] < target
     */
    public int threeSumSmaller(int[] nums, int target) {
        // Write your code here
        if (nums.length < 3) return 0;
        Arrays.sort(nums);
        if (nums[0] >= target) return 0;
        int count = 0;
        for (int i = 0; i < nums.length-2; i++) {
            int start = i+1, end = nums.length-1;
            int sum = target - nums[i];
            while (start < end) {
                if (nums[start] + nums[end] < sum) {
                    count += end-start;
                    start++;
                } else {
                    end--;
                }
            }
        }
        return count;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/69649.html

相关文章

  • [Leetcode] 3Sum Smaller 三数较小和

    摘要:排序法复杂度时间空间思路解题思路和一样,也是先对整个数组排序,然后一个外层循环确定第一个数,然后里面使用头尾指针和进行夹逼,得到三个数的和。 3Sum Smaller Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 = target){ ...

    tomato 评论0 收藏0
  • 3Sum Smaller

    摘要:题目链接,从小到大排序固定第一个数字,从后面的数字里选第二个第三个后两个数字,用来找,从开始因为所有之间的数和组合都 3Sum Smaller 题目链接:https://leetcode.com/problems... sort,从小到大排序 固定第一个数字index = i,从后面的数字里选第二个第三个 后两个数字,用2 points来找,从j = i + 1, k = len(...

    Salamander 评论0 收藏0
  • [LintCode/LeetCode] 3Sum Closest

    摘要:这个题和的做法基本一样,只要在循环内计算和最接近的和,并赋值更新返回值即可。 Problem Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three intege...

    ShevaKuilin 评论0 收藏0
  • [LintCode/LeetCode] 3Sum

    摘要:双指针法的解法。然后用和夹逼找到使三数和为零的三数数列,放入结果数组。对于这三个数,如果循环的下一个数值和当前数值相等,就跳过以避免中有相同的解。 Problem Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplet...

    Sunxb 评论0 收藏0
  • [LintCode] Count of Smaller Number [二分法的活用]

    摘要:由于这道题目不是查找而是选择第一个的数的位置,所以语句里面可以把和归为同一个分支,因为存在包含重复数的情况,所以要和一样,指针前移替换。那么另一个分支,除了将后移,还要更新返回值。约束条件为的两种写法 Problem Give you an integer array (index from 0 to n-1, where n is the size of this array, va...

    2json 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<