[LeetCode]016-3Sum-Closest
2015-12-07 18:32
323 查看
题目:
3Sum Closest
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).
Solution:
解法就是上一题思路的延伸。
1、先排序
2、求和,与target比较
3、找出相距最小的和
3Sum Closest
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).
Solution:
解法就是上一题思路的延伸。
1、先排序
2、求和,与target比较
3、找出相距最小的和
int threeSumClosest(vector<int>& nums, int target) { int i,j,k; int n = nums.size(); if(n<3) return 0; int min_value = abs(nums[0]+nums[1]+nums[2] - target); int result = nums[0]+nums[1]+nums[2]; QuickSort(nums,0,n-1); for(i=0;i<n;i++) { int current_num = nums[i]; j = i+1; k = n-1; while(j<k) { int sum = nums[j] + nums[k] + current_num; if(sum - target < 0) { j++; } else if(sum - target > 0) { k--; } else { result = sum; return result; } if(abs(sum-target) < min_value) { min_value = abs(sum-target); result = sum; } } } return result; } void QuickSort(vector<int>& nums,int low,int high) { if(low<high) { int pivot = nums[low]; int first = low; int last = high; while(first<last) { while(nums[last] >= pivot && first <last) { last--; } nums[first] = nums[last]; while(nums[first] < pivot && first <last) { first++; } nums[last] = nums[first]; } nums[first] = pivot; QuickSort(nums,low,first-1); QuickSort(nums,first+1,high); } else return; }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解