3sum-closest(最近三数之和)

https://www.nowcoder.com/practice/291a866d7c904563876b373b0b157dde?tpId=46&tqId=29162&tPage=4&rp=4&ru=/ta/leetcode&qru=/ta/leetcode/question-ranking

n^3的做法.把所有情况都列举出来

class Solution {
public:
    int threeSumClosest(vector<int> &num, int target) {
        int n = num.size();
		if(n < 3)
			return -1;

		int limit = INT_MAX;//接近程度,初始为INT最大值
		int res = 0;
		for(int i = 0; i <= n - 3; i++){
			for(int j = i + 1; j <= n - 2; j++){
				for(int k = j +1; k <= n - 1; k++){
					

					int sum = num[i] + num[j] + num[k];
					if(abs(sum - target) < limit){
	
						limit = abs(sum - target);
						res = sum;
						
					}
				}
			}
		}
		return res;
    }
};

n^2做法。先排序。


class Solution {
public:
    int threeSumClosest(vector<int> &num, int target) {
        int n = num.size();
		if(n < 3)
			return -1;

		int limit = INT_MAX;//接近程度,初始为INT最大值
		int res = -1;

		sort(num.begin(), num.end() );
		for(int i = 0; i <= n- 3; i++){
			int next = i +1;//指向当前的下一个
			int last = n - 1;//指向尾部
			while(next < last){
				int sum = num[i] + num[next] + num[last];//当前和
				if(abs(sum - target) < limit){//比较接近
					limit = abs(sum - target);
					res = sum;
				}
				if(sum < target)//小于目标就next++,寻找更大的和
					next++;
				else//大于或者等于的时候就缩小,寻找更小的和
					last--;
			}

			
		}

		return res;

    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值