[LeetCode]016-3Sum-Closest
来源:互联网 发布:python数据分析书籍 编辑:程序博客网 时间:2024/06/08 02:56
题目:
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; }
0 0
- LeetCode 016 3Sum Closest
- LeetCode 016 3Sum Closest
- LeetCode 016 3Sum Closest
- [LeetCode]016-3Sum-Closest
- LeetCode 016 3Sum Closest
- LeetCode 016 3Sum Closest
- LeetCode-016 3Sum Closest
- LeetCode: 3 Sum Closest
- leetcode - 3 sum closest
- leetcode 3Sum Closest
- LeetCode: 3Sum Closest
- [Leetcode]3Sum Closest
- Leetcode: 3SUM Closest
- LeetCode 3Sum Closest
- [Leetcode] 3Sum Closest
- LeetCode : 3Sum Closest
- LeetCode 3Sum Closest
- [LeetCode] 3Sum Closest
- 微信公众号开发:用户授权获取用户信息
- iOS耗电测试工具--batterydetective
- HandlerThread 的使用
- memcached学习笔记1(windows 7 64bit 环境下安装memcached)
- 配置Apache svn 服务器
- [LeetCode]016-3Sum-Closest
- Android 和 iOS 的区别
- week14---12月8日 JS内置对象——string、Date
- next()与nextLine()
- 一些iOS常用的第三方库和控件
- 【2015广东工业大学新生赛A】【排序 二进制数位思想】GG和女神 数字按照数值排序后取了多少个数
- Opencv 任意区域选中
- http 头信息详解
- 亲情无价