259. 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?

**解题思路 **
Binary Search Using n O(n2) runtime
注意: all hi in (lo, hi] will also satisfy the condition , 所以是 count += hi - lo 而不是count++;

    public int threeSumSmaller(int[] nums, int target) {
        int count = 0;
        Arrays.sort(nums);
        int len = nums.length;
        
        for (int i = 0; i < len - 2; i++) {
            int lo = i + 1, hi = len - 1;
            while (lo < hi) {
                if (nums[i] + nums[lo] + nums[hi] >= target) {
                    hi--;
                } else {
                    count += hi - lo;  // all hi in (lo, hi] will also satisfy the condition
                    lo++;
                }
            }
        }
        return count;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Given an array of n integers nums and a target, find the ...
    matrxyz阅读 1,423评论 0 0
  • Given an array of n integers nums and a target, find the ...
    Jeanz阅读 1,544评论 0 0
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,354评论 0 33
  • 我不知道有没有人和我一样,对自己目前生活的不满,很想改变,但因为不够自律,但又总是止于想,无行动。于是也就...
    水纸舟阅读 3,587评论 0 0
  • 人生头一次接触板绘呐,还用不太熟练,绘画功底也不够的哈,哈哈哈……笑出声了,这图一晚上撸出来的,以后再接再厉…
    大触佡阅读 1,562评论 0 0

友情链接更多精彩内容