• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: 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具体是什么,只关心个数,所以可以排序

 1 public class Solution {
 2     public int threeSumSmaller(int[] nums, int target) {
 3         int res = 0;
 4         Arrays.sort(nums);
 5         for (int i=nums.length-1; i>=2; i--) {
 6             //if (i!=nums.length-1 && (nums[i]==nums[i+1])) continue;
 7             res += twoSum(nums, 0, i-1, target-nums[i]);
 8         }
 9         return res;
10     }
11     
12     public int twoSum(int[] nums, int l, int r, int target) {
13         int sum = 0;
14         while (l < r) {
15             if (nums[l]+nums[r] < target) {
16                 sum += r-l;
17                 l++;
18             }
19             else {
20                 r--;
21             }
22         }
23         return sum;
24     }
25 }

 

posted @ 2015-12-23 04:47  neverlandly  阅读(322)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3