首页 技术 正文
技术 2022年11月14日
0 收藏 455 点赞 2,314 浏览 1449 个字

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?


题目标签:Array

  题目给了我们一个 nums array 和一个 target, 要我们找到 任何三个数字之和 小于 target。题目要求了要 O(n^2) 的runtime, 所以三个 for loop 就不行了,虽然也能通过。

  对于这种3Sum,要在O(n^2) 条件下的,都是要一个遍历,然后剩下的n*n 用 two pointers 来代替。换句话说,就是第一个遍历来选定第一个数字,剩下的就是2Sum的题目了,而且要用 two pointers 来做。

  来分析一下这题的情况:

  首先排序,从小到大。

  选好第一个数字,然后在剩下的数字里,选好left 和 right:

          case 1:如果当left 数字 + right 数字 < target – 第一个数字  的话, 意味着符合条件,并且left 和 所有在right 左边的数字搭配 也都符合,因为排序从小到大,所以直接把所有的可能性都加上, right – left;然后left++ 到下一个数字继续。

          case 2:如果当left 数字 + right 数字 >= target – 第一个数字  的话, 意味着目前数字组合太大,需要更小的数字,所以right–。

Java Solution:

Runtime beats 79.74%

完成日期:09/08/2017

关键词:Array

关键点:一个遍历(选中第一个数字):two pointers 代替 n*n

 class Solution
{
public int threeSumSmaller(int[] nums, int target)
{
Arrays.sort(nums);
int res = 0; for(int i=0; i<nums.length-2; i++) // no need to iterate last two numbers
{
int left = i+1;
int right = nums.length-1;
int tempTarget = target - nums[i]; while(left < right)
{ // if find two numbers < tempTarget
if(nums[left] + nums[right] < tempTarget)
{
res += (right - left); // all the left side numbers are also < tempTarget
left++; // left one with each number from right rest are done, move to next left one
}
else // meaning current two numbers sum is too big, need smaller one
right--;
} } return res;
}
}

参考资料:N/A

LeetCode 算法题目列表 – LeetCode Algorithms Questions List

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,493
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,495
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,133
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,297