三者相加最接近给定值的和

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

这里我自己用了比较器的用法,没办法,是偏爱

	public int threeSumClosest(int[] nums, int target) {
		Map<Integer, Integer> map = new HashMap<Integer, Integer>();
		
        if(nums.length < 3 || nums ==null) {
        	 return 0;  
        }         
        Arrays.sort(nums);
        int closeest =0;
        for(int i=0;i<=nums.length-3;i++) {
        	
        	int minIndex = i+1;
        	int maxIndex = nums.length -1;
        	
        	while(minIndex<maxIndex) {//当最小index小于最大时
        		int sum = nums[i]+nums[minIndex]+nums[maxIndex];
        		int k = sum-target;
            	if(k>0) {
            		map.put(k,sum);
            		maxIndex--;
            	}else if(k<0) {
            		map.put(-k,sum);
            		minIndex++;
            	}else {
            		return sum;
            	}
        	}
        }
        List<Map.Entry<Integer, Integer>> result = new ArrayList<Map.Entry<Integer,Integer>>();
        result.addAll(map.entrySet());
        Collections.sort(result, new Comper2());
        closeest = result.get(0).getValue();
        System.out.println(closeest);
        return closeest;
    }//还是运用上次那个求三者和为0的思想,这次把它放入哈希表,不知道为啥,总是想用哈希表,哈哈哈
	
	
//定义一个比较器,一直用的化最好还是写个工具类出来哈,
//由于leetCode 不能识别这个比较类,所以我自己测了一下,1784970纳秒马马虎虎吧
class Comper2 implements Comparator<Map.Entry<Integer,Integer>>{//比较key

	public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {//比较value
		
		return o1.getKey() - o2.getKey();
	}
 }

我这就是笨办法了,
然后看了一下别人的解答,前面其实一样,主要是后面

public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int sum=0, minDiff=Integer.MAX_VALUE, sumWithMinDiff=0, diff=0;
        for(int i=0; i<nums.length-2; i++){
            if(i>0 && nums[i]==nums[i-1])
                continue;
            int first=i+1;
            int last=nums.length-1;
            while(first<last){
               sum=nums[i]+nums[first]+nums[last];
                if(sum==target){
                   return sum; 
                }
                else if(sum<target)
                    first++;
                else if(sum>target)
                    last--;
               diff=Math.abs(sum-target);//在这里用了数学公式,求绝对值
               if(diff<minDiff){
                   minDiff=diff;
                   sumWithMinDiff=sum;
               }
                
            }
        }
        return sumWithMinDiff;
		
    }

这么一想的话,好像我做的饶了一大圈,直接比较就好了,是我败了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值