zoukankan      html  css  js  c++  java
  • 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?
    
    Show Company Tags
    Show Tags
    Show Similar Problems

    小心这里是index triplets, 不是nums[i]数组元素的triplets, 所以3Sum那道题里面的跳过条件不用了

    因为不关心每个index具体是什么,只关心个数,所以可以排序

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

      

  • 相关阅读:
    python 购物车和三级菜单
    python-装饰器
    day3 python 函数
    day3 python 集合 文件
    two day python基础知识
    python-day 1
    Cordova 环境搭建
    javascript在html直接传值
    JavaScript疑难点
    Javascript创建对象的方法
  • 原文地址:https://www.cnblogs.com/apanda009/p/8072504.html
Copyright © 2011-2022 走看看