本文共 1427 字,大约阅读时间需要 4 分钟。
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]]
在这道题中是要在给定的数组中选择三个数字使得他们相加得到的和等于目标值。那么思路就是,首先将一组数组先进行排序;然后从第一个数组开始,先选择一个数字,然后再寻找另外两个数字使得三个数字的和达到要求(第二个数字的搜索起点是第一个数字的后一位,第三个数字的搜索位置是数组的末尾开始)。在计算的过程中可能计算结果分为如下3中情况:
(1)和等于目标值,这种情况满足了题目的要求,是一个可行的解,记录
(2)和大于目标值,这种情况下代表三个数字中最大的第三个数字过大了,就需要将第三个数字向左移动,来得到更小的和
(3)和小于目标值,这种情况下代表三个数字中最小的第而个数字过小了,就需要将第三个数字向右移动,来得到更大的和
class Solution {public: vector> threeSum(vector & nums) { int len(nums.size()); sort(nums.begin(), nums.end()); int left(0), right(0); vector > value; for(int i=0; i 0 && nums[i]==nums[i-1]) continue; //如果当前数和前一个数相同跳过,因为计算过了 left = i+1; //搜索的起始位置是当前位置的下一个 right = len-1; //搜索的结束位置是最后的位置 while(left < right) { int sum = nums[left] + nums[i] + nums[right]; if(0 == sum) { vector temp(3, 0); //申请3个int空间单位的vec temp[0] = nums[left]; temp[1] = nums[i]; temp[2] = nums[right]; value.push_back(temp); //在这里加入判断重复 while(left 0) //计算得到的结果偏大,那么就向左移动,因为左边的数小 --right; if(sum < 0) //计算得到的结果偏小,那么就向右移动,因为右边的数大 ++left; } } return value; }};
转载地址:http://hfkhj.baihongyu.com/