LeetCode 259. 3Sum Smaller
2016-05-04 03:25
357 查看
Two pointers.
#include <vector> #include <algorithm> #include <iostream> using namespace std; /* 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]. */ int threeSumSmaller(vector<int>& nums, int target) { if(nums.size() < 3) return 0; sort(nums.begin(), nums.end()); int count = 0; for(int i = 0; i < nums.size(); ++i) { int start = i + 1; int end = nums.size() - 1; while(start < end) { if(nums[i] + nums[start] + nums[end] < target) { count += end - start; start++; } else { end--; } } } return count; } int main(void) { vector<int> nums{-2, 0, 1, 3}; cout << threeSumSmaller(nums, 2) << endl; }
相关文章推荐
- 如何使用psql命令去调试含参的sql文件
- LeetCode 198. House Robber(小偷游戏)
- SQLite错误码
- android Camera SurfaceView变形,为什么?
- LeetCode 191. Number of 1 Bits(比特数)
- NYOJ-1070-诡异的电梯[Ⅰ]
- java中的foreach循环
- 门面模式和中介者模式
- LeetCode 190. Reverse Bits(翻转比特)
- NAS
- http笔记
- 关系数据库常用SQL语句语法大全
- linux重定向及nohup不输出的方法
- 冒泡排序的例题讲解
- JDK中的设计模式
- cocos2d-lua+cocos studio之ListView加载Item
- [python]常见数据结构归纳
- 时光隽永,少年何惑
- Provisioning Services 7.8 入门系列教程之四 目标设备安装
- Provisioning Services 7.8 入门系列教程之四 目标设备安装