3Sum Smaller
来源:互联网 发布:如何正确下载软件 编辑:程序博客网 时间:2024/04/20 09:00
Given an array of n integers nums and a target, find the number of index tripletsi, j, k
with0 <= i < j < k < n
that satisfy the conditionnums[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?
sum >target的时候,k--;没有什么问题;
sum == target的时候,j,j+1,.....k-1, k,那么从j到k之间的nums[k] 绝对小于target,这样count += k-j;
再j开始挪动。这样j++;
这个题目跟之前的3sum的不同就是,== target的时候,j,k不能同时移动,要记住题目要求什么。
public class Solution { public int threeSumSmaller(int[] nums, int target) { if(nums == null || nums.length == 0) return 0; int count = 0; Arrays.sort(nums); for(int i=0; i<nums.length-2; i++){ int j=i+1; int k=nums.length-1; while(j<k){ int sum = nums[i] + nums[j] + nums[k]; if(sum >= target){ k--; } else { // sum < target; count += k-j; j++; } } } return count; }}
0 0
- LeetCode-3Sum Smaller
- [Leetcode]3Sum Smaller
- [LeetCode259]3Sum Smaller
- 3Sum Smaller
- 3Sum Smaller
- 259. 3Sum Smaller
- 259. 3Sum Smaller
- Leetcode-259. 3 Sum Smaller
- [leetcode 259]3Sum Smaller
- [leetcode] 259. 3Sum Smaller
- [LeetCode]259. 3Sum Smaller
- LeetCode 259. 3Sum Smaller
- LeetCode 359. 3Sum Smaller
- LeetCode 题解(270) : 3Sum Smaller
- [leetcode] 259. 3Sum Smaller 解题报告
- Leetcode 259. 3Sum Smaller (Medium) (cpp)
- [Leetcode] 259. 3Sum Smaller 解题报告
- 【Leetcode】3Sum,3sum closest,3sum smaller, 4Sum
- Singleton
- 身份证 验证
- 禁用sublime自动更新提示
- Httpurlconnection多文件上传问题。
- Hbase启动从节点报错:FATAL org.apache.hadoop.hbase.regionserver.HRegionServer:...ClockOutOfSyncException
- 3Sum Smaller
- POJ 2942 点双联通+二分图染色
- 蓝鸥Unity开发基础—— 二维数组学习笔记
- makefile从shell中获取要跑的testcase
- 字符串前缀:字典树(Trie)的应用
- Regularized least-squares classification(RLSC)
- [leetcode] 78. Subsets
- java.util.TreeMap
- c/c++中整型数据的数据范围