zoukankan      html  css  js  c++  java
  • 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;
        }
    }
    
  • 相关阅读:
    PAT:1002. 写出这个数 (20) AC
    PAT:1031. 查验身份证(15) AC
    PAT:1021. 个位数统计 (15) AC
    NSDate
    iOS程序的生命的周期
    Swift swith语句
    Swift 循环语句
    Swift 基本运算符
    Swift 解包
    Swift 可选类型(补充)
  • 原文地址:https://www.cnblogs.com/reboot329/p/5958934.html
Copyright © 2011-2022 走看看