13_leetcode_3Sum Closest
2014-06-05 08:12
260 查看
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.
1.数组排序;2.当找到三个元素的值与目标值相等,直接返回 3.找到最接近的情况,分为大于目标值和小于目标值两种情况
int threeSumClosest(vector<int> &num, int target)
{
if(num.size() <= 2)
return 0;
int result = num[0] + num[1] + num[2];
sort(num.begin(), num.end());
int size = (int)num.size();
for(int i = 0; i < size - 2; i++)
{
if(i == 0 || num[i] != num[i-1])
{
int leftValue = target - num[i];
int left = i + 1;
int right = size - 1;
while(left < right)
{
if(num[left] + num[right] == leftValue)
{
return target;
}
else if(num[left] + num[right] > leftValue)
{
if(num[left] + num[right] - leftValue <= abs(result - target))
{
result = num[left] + num[right] + num[i];
}
right--;
}
else
{
if(leftValue - num[left] - num[right] <= abs(result - target))
{
result = num[left] + num[right] + num[i];
}
left++;
}
}
}
}
return result;
}
exactly one solution.
1.数组排序;2.当找到三个元素的值与目标值相等,直接返回 3.找到最接近的情况,分为大于目标值和小于目标值两种情况
int threeSumClosest(vector<int> &num, int target)
{
if(num.size() <= 2)
return 0;
int result = num[0] + num[1] + num[2];
sort(num.begin(), num.end());
int size = (int)num.size();
for(int i = 0; i < size - 2; i++)
{
if(i == 0 || num[i] != num[i-1])
{
int leftValue = target - num[i];
int left = i + 1;
int right = size - 1;
while(left < right)
{
if(num[left] + num[right] == leftValue)
{
return target;
}
else if(num[left] + num[right] > leftValue)
{
if(num[left] + num[right] - leftValue <= abs(result - target))
{
result = num[left] + num[right] + num[i];
}
right--;
}
else
{
if(leftValue - num[left] - num[right] <= abs(result - target))
{
result = num[left] + num[right] + num[i];
}
left++;
}
}
}
}
return result;
}
相关文章推荐
- LeetCode (13): 3Sum Closest
- Leetcode:3Sum Closest
- LeetCode之“散列表”:Two Sum && 3Sum && 3Sum Closest && 4Sum
- [Leetcode]3Sum Closest
- [leetcode]3Sum Closest
- [leetcode]16. 3Sum Closest
- [LeetCode]3Sum Closest
- 【LeetCode】3Sum Closest
- Leetcode016 3Sum Closest
- [Leetcode]3Sum Closest
- leetcode 16 3Sum Closest
- 【LeetCode】LeetCode——第16题:3Sum Closest
- [Leetcode] 3Sum Closest
- [Leetcode] 16. 3Sum Closest
- LeetCode 16 3Sum Closest
- leetcode-3sum closest
- leetcode: 3SumClosest
- leetcode16. 3Sum Closest
- 【LeetCode】3Sum Closest
- leetcode:2sum,2sumSorted,3sum,3sumClosest,4sum,4sumII.[哈希表,双指针]