leetcode 3Sum
来源:互联网 发布:乐视线刷软件 编辑:程序博客网 时间:2024/06/08 02:20
1、
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
- For example, given array S = [-1, 0, 1, 2, -1, -4],
- A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
题意:给定一个数组,从中找出所有和为零的三个数,要求结果不重复
思路:从头开始遍历,对每一个数找到两个数和为它的相反数,先排序,然后从两头向中间找,注意找出所有情况和去除重复数字,时间复杂度O(n^2)。
class Solution {public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> res; std::sort(nums.begin(), nums.end()); for (int i = 0; i < nums.size(); ++i) { int target = -nums[i]; int front = i + 1; int back = nums.size() - 1; while (front < back) { int sum = nums[front] + nums[back]; if (sum < target) front++; else if (sum > target) back--; else { vector<int> tmp(3, 0); tmp[0] = nums[i]; tmp[1] = nums[front]; tmp[2] = nums[back]; res.push_back(tmp); //跳过重复数字 while (front < back && nums[front] == tmp[1]) front++; while (front < back && nums[back] == tmp[2]) back--; } } //跳过重复数字 while (i + 1 < nums.size() && nums[i + 1] == nums[i]) i++; } return res; }};
2、Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1.The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
题意:给定S个整数和一个目标数,在S个整数中找出三个数,使他们的和距离目标数最近,结果唯一。
思路:同上,时间复杂度O(n^2);
class Solution {public: int threeSumClosest(vector<int>& nums, int target) { if (nums.size() < 3) return 0; int closest = nums[0] + nums[1] + nums[2]; std::sort(nums.begin(), nums.end()); for (int i = 0; i < nums.size() - 2; ++i) { int front = i + 1, back = nums.size()-1; while (front < back) { int tmp = nums[i] + nums[front] + nums[back]; if (tmp == target) return tmp; if (abs(target - tmp) < abs(target - closest)) closest = tmp; if (tmp > target) --back; else ++front; } while (i + 1 < nums.size() && nums[i] == nums[i+1]) ++i; } return closest; }};
阅读全文
0 0
- 【Leetcode】3Sum (Sum)
- Leetcode:2Sum,3Sum
- 【Leetcode】3Sum Closest (Sum)
- leetcode 2 sum 3sum 4sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- [LeetCode] 2Sum, 3Sum, 4Sum, 3SUm closet
- [LeetCode] K sum(2Sum、3Sum、4Sum)
- leetcode--sum集合:2sum,3sum,4sum
- leetcode --- 2 sum , 3 sum , 4 sum , k sum problem
- LeetCode: 3Sum
- LeetCode: 3 Sum Closest
- leetcode - 3 Sum
- leetcode - 3 sum closest
- leetcode 3Sum
- leetcode 3Sum Closest
- LeetCode: 3Sum
- elasticsearch.yml 配置
- poj2318 Toys 【计算几何】
- FATE
- 最适合初学者的 IntelliJ IDEA 教程 (2)- 最常见的显示设置和快捷键
- CentOS下通过yum安装nodejs等
- leetcode 3Sum
- python_20171122_python3.6.1 pd.read_csv()输入中文路径OSError: Initializing from file failed
- NLTK自带的词干提取器
- PC端的神器软件
- Python运维自动化开发之Fabric模块
- idea 创建 java web项目(图文)
- 使用request-promise验证url的可访问性
- 增删改查
- 32位Linux系统的虚拟地址映射 <二>