【LeetCode】259 3Sum Smaller
2024-09-08 16:22:00
题目:
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(n^2) runtime?
题解:
(我没舍得花钱。。。咳咳,这样不太好QAQ,代码都没有提交过,所以以后来看得注意一下代码的正确性。)
老规矩,第一个想法是啥?必须的暴力解啊,哈哈,虽然时间复杂度是O(n^3);这里
Solution 1 ()
class Solution {
public:
int threeSumSmaller(vector<int>& nums, int target) {
int cnt = ;
sort(nums.begin(), nums.end());
int n = nums.size();
for(int i=; i<n-; i++) {
if(i> && nums[i] == nums[i-]) continue;
for(int j=i+; j<n-; j++) {
if(j>i+ && nums[j] == nums[j-]) continue;
for(int k=j+; k<n; k++) {
if(k>j+ && nums[k] == nums[k-]) continue;
if(nums[i] + nums[j] + nums[k] < target) cnt++;
else break;
}
}
}
}
};
若想时间复杂度为O(n^2),那么就需要和之前的3Sum题目一样,两指针为剩余数组的头尾指针,搜索遍历。这里需要注意的是,当sum<target时,cnt需要加上k-j,而不是cnt++,因为数组已经排好序,若尾指针当处于位置k时满足条件,则j<position<=k的pos都满足这个条件,故cnt需加上k-j.
Solution 2 ()
class Solution {
public:
int threeSumSmaller(vector<int>& nums, int target) {
int cnt = ;
sort(nums.begin(), nums.end());
int n = nums.size();
for(int i=; i<n-; i++) {
if(i> && nums[i] == nums[i-]) continue;
int j = i + , k = n - ;
while(j<k) {
int sum = nums[i] + nums[j] + nums[k];
if(sum < target) {
cnt += k - j;
j++;
}
else k--;
}
}
return cnt;
}
};
最新文章
- json、javaBean、xml互转的几种工具介绍
- SQL 里解析 XML 格式 字段 信息
- 最大似然判别法和Bayes公式判别法
- parentNode的兼容性问题
- 还是畅通工程(MST)
- 关闭MyEclipse代码编辑器(breadcrumb)工具条
- Jenkins学习之——(2)插件的安装
- mac隐藏或显示文件
- Objective-C路成魔【11-多态性、动态类型和动态绑定】
- AngularJS的工作原理1
- digitalocean注册验证账户、激活账号教程
- CentOS服务器下JavaEE环境搭建指南(远程桌面+JDK+Tomcat+MySQL)
- Pandas 把数据写入csv
- Python中的 @staticmethod@classmethod方法
- nginx配置学习总结
- jquery完成界面无刷新加载登陆注册
- Python3.5+SQL+Prometheus+Grafana报表/监控
- 【laravel5.4】查询构造器对象与模型instance的互相换换
- delphi XE8 NetHTTPRequest NetHTTPClient
- Spring SetFactoryBean实例