题目:

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;
}
};

最新文章

  1. json、javaBean、xml互转的几种工具介绍
  2. SQL 里解析 XML 格式 字段 信息
  3. 最大似然判别法和Bayes公式判别法
  4. parentNode的兼容性问题
  5. 还是畅通工程(MST)
  6. 关闭MyEclipse代码编辑器(breadcrumb)工具条
  7. Jenkins学习之——(2)插件的安装
  8. mac隐藏或显示文件
  9. Objective-C路成魔【11-多态性、动态类型和动态绑定】
  10. AngularJS的工作原理1
  11. digitalocean注册验证账户、激活账号教程
  12. CentOS服务器下JavaEE环境搭建指南(远程桌面+JDK+Tomcat+MySQL)
  13. Pandas 把数据写入csv
  14. Python中的 @staticmethod@classmethod方法
  15. nginx配置学习总结
  16. jquery完成界面无刷新加载登陆注册
  17. Python3.5+SQL+Prometheus+Grafana报表/监控
  18. 【laravel5.4】查询构造器对象与模型instance的互相换换
  19. delphi XE8 NetHTTPRequest NetHTTPClient
  20. Spring SetFactoryBean实例

热门文章

  1. 兔子--改动Android Studio的快捷键,改动成eclipse的快捷键
  2. H5缓存机制学习记录
  3. python 安装protobuf
  4. 认识XmlReader
  5. NuGet管理工具安装
  6. 【BZOJ1222】[HNOI2001]产品加工 DP
  7. 【BZOJ1499】[NOI2005]瑰丽华尔兹 单调队列+DP
  8. 九度OJ 1042:Coincidence(公共子序列) (DP)
  9. detached HEAD state
  10. 空间Rm的任意两个范数都互相等价