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?

Solution:two pointers

思路: Just basically same with other "sum"
但要求的是的count,所以count += right - left. 双指针和满足<target的情况下,right左减到底也都满足。然后再升加left,继续此过程。
Time Complexity: O(N) Space Complexity: O(N)

Solution Code:

public class Solution {
    
    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 left = i+1, right = len - 1;
            while(left < right) {
                if(nums[i] + nums[left] + nums[right] < target) {
                    count += right - left;
                    left++;
                } else {
                    right--;
                }
            }
        }
        
        return count;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,776评论 0 33
  • 每过一段时间,我们应该要回想一下自己曾经走过的路。 写作从去年开始到现在已经有差不多100天时间(我是说持续写作无...
    豆豆掌门阅读 437评论 12 11
  • 我有一个法国闺蜜,早上六点半,看到皮特朱莉申请离婚的新闻。太激动了,立马拉了个群:“姐妹们,皮特自由了,我们怎么办...
    卢璐说阅读 4,402评论 1 47
  • 1 很久没有过朝九晚五的坐班生活了,电脑都陌生了,唯有五笔打字没有忘记,还是那么快速的敲击。 简书也荒了,今天去一...
    张杨张扬阅读 236评论 0 1