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?
[分析]
延续3Sum & 3Sum Closest的基本套路,先排序输入数组,固定第一个数后在剩余数组区间中寻找所有满足条件的另外两个数,使用two pointers技巧进行寻找。
关键点是一旦找到 i, j 满足nums[i] + nums[j] + nums[k] < target, 因为数组已排序,则(i, j-1, k),(i, j - 2, k)...(i, i+1, k)均是满足条件的解,这些解总共是 j - i个,而无需一个一个check它们。
此外需注意此题不需要去重处理,一开始画蛇添足进行了去重处理……
很开心思路和leetcode讨论版的最佳思路一致~
public class Solution {
public int threeSumSmaller(int[] nums, int target) {
if (nums == null || nums.length < 3)
return 0;
Arrays.sort(nums);
int counter = 0;
int end = nums.length - 3;
for (int k = 0; k <= end; k++) {
int i = k + 1, j = nums.length - 1;
while (i < j) {
int sum3 = nums[i] + nums[j] + nums[k];
if (sum3 < target) {
counter += j - i;
i++;
} else {
while (i < --j && nums[j] == nums[j + 1]);
}
}
}
return counter;
}
}
分享到:
相关推荐
《leetcode-solutions》,刷算法题,需要有一定的英文阅读能力。。。
Algorithm-LeetCode-Sol-Res.zip,干净,易懂的解决方案和资源,为leetcode在线判断算法问题。,算法是为计算机程序高效、彻底地完成任务而创建的一组详细的准则。
IDEA 插件,lettcode刷题,leetcode-editor7.4版本下载进行本地导入(直接将压缩包拖进IDEA即可)
Algorithm-leetcode-spider.zip,leetcode公司,算法是为计算机程序高效、彻底地完成任务而创建的一组详细的准则。
leetcode-cli-plugins leetcode-cli 的第 3 方插件。 什么是 如何使用 如何使用 插件 名称 描述 增强的命令 按公司或标签过滤问题 list 不要在同一台计算机上使 Chrome 的会话过期 login 不要在同一台计算机上使 ...
在IDE中解决LeetCode问题,支持leetcode.com与leetcode-cn.com,满足基本的做题需求。 理论上支持: IntelliJ IDEA PhpStorm WebStorm PyCharm RubyMine AppCode CLion GoLand DataGrip Rider MPS Android Studio。
解题思路思路和LeetCode-python 503.下一个更大元素 II一致,只是这里求的是下标的距离,而不是数值倒序搜索,用到栈,栈里存储索引情况1:若栈为
leetcode 答案解析 golang解答
leetcode-cheat 的发布 它是什么 ? 这是一个chrome 扩展,可以帮助您更高效地使用 leetcode。您可以从 重要: leetcode-cheat 现在只支持中文版。 也就是说不完全支持leetcode.com,但是你可以用leetcode-cn.com代替...
~/.vscode/extensions/leetcode.vscode-leetcode-0.17.0/node_modules/vsc-leetcode-cli/bin/leetcode /usr/local/bin/leetcode 修改模板 open ~/.vscode/extensions/leetcode.vscode-leetcode-0.17.0/node_modules/...
leetcode-editor,在ide中做leetcode练习,支持leetcode.com和leetcode-cn.com,以满足练习的基本需求。理论上支持:intellij idea phpstorm webstorm pycharm rubymine appcode clion goland datagrip rider mps ...
主要介绍了LeetCode -- Path Sum III分析及实现方法的相关资料,希望通过本文能帮助到大家,需要的朋友可以参考下
leetcode-helper-1.7.1
leetcode-tag-dynamic programming
然后进入到LeetCode-Spider目录中修改config.json,其中outputDir需要填写该工程的/docs/views文件夹路径 { "username": "aaa", "password": "bbb", "outputDir": "/Users/liuyao/Downloads/LeetCode-Blog-Test/docs...
leetcode-cli 注意:这个存储库是为了临时使用而分叉的。 注意:从 webbrowser 复制 cookie 并使用leetcode user -c可以临时修复不能。 一个享受 leetcode 的高效 cli 工具! 非常感谢 leetcode.com,一个非常棒的...
leetcode-tag-Tree
leetcode-tag-Stack
leetcode-问题-爬虫 目录由cd problems && npx leetcode-problems-crawler -r 1-10生成cd problems && npx leetcode-problems-crawler -r 1-10 用法 爬行问题1到5: $ npx leetcode-problem-crawler -r 1-5 爬行问题...