259. 3Sum Smaller

最后更新

二刷。

好蠢,直接按3sum做的,还在想有什么意义。

这个题有巧办法,3个数的和小于target的时候,nums[i], nums[l] + (l, r]范围内的所有值都小于target,直接加数量就可以了。。

public class Solution {
    public int threeSumSmaller(int[] nums, int target) {
        int res = 0;
        Arrays.sort(nums);
        
        for (int i = 0; i < nums.length; i++) {
            int l = i + 1;
            int r = nums.length - 1;
            
            while (l < r) {
                int total = nums[i] + nums[l] + nums[r];
                if (total >= target) {
                    r --;
                } else {
                    res += (r - l);
                    l ++;
                }
            }
        }
        return res;
    }
}

一刷

滑窗。。

和上一个3 SUM不同的是,一旦判定成功就有一个范围了,比如L-R符合,那么R减少到L之前所有组合都可以,直接加上就行了,然后L++,继续判断不行就缩小R。

和3 SUM几乎完全一样的。。而且不用判断相等的情况。

public class Solution 
{
    public int threeSumSmaller(int[] nums, int target) 
    {
        int res = 0;
        if(nums.length <= 2) return res;
        Arrays.sort(nums);
        
        for(int i = 0; i < nums.length-2;i++)
        {
            int t = target - nums[i];
            int l = i+1;
            int r = nums.length-1;
            while(l < r)
            {
                int temp = nums[l] + nums[r];
                if(temp < t)
                {
                    res += r-l;
                    l++;
                }
                else
                {
                    r--;
                }
            }
            
            //while(i < nums.length-2 && nums[i] == nums[i+1]) i++;
        }
        
        return res;
    }
}
posted @ 2016-10-14 06:03  哇呀呀..生气啦~  阅读(82)  评论(0编辑  收藏  举报