【leetcode -16】3Sum Closest

【leetcode -16】3Sum Closest

/*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.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
*/

public class Solution16 {
	
	    public int threeSumClosest(int[] nums, int target) {
			   int min=Integer.MAX_VALUE;
			   int len=nums.length;
	           int r=0;
	           Arrays.sort(nums);//排序
			   if(len==0) {
	        	   r=0;
	        	   
	           }else if(len==1){
	        	   r=nums[0];
	        	   
	           }else if(len==2) {
	        	   r=nums[0]+nums[1];
	           }else {
	        	   r=nums[0]+nums[1]+nums[2];
	           }
			   
			   for(int i=0;i<len;i++) {
				   int L=i+1;
				   int R=len-1;
				   while(L<R) {
				   int value=nums[i]+nums[L]+nums[R];
				   int tap=Math.abs(target-value);
				   if(tap<min) {
					   min=tap;
	                   r=value;
				   }
				   if(min==0) {
					  return r;
				   }
				   else if(target<value) {
					   R--;
				   }else if(target>value) {
					   L++;
				   }
				   
				   
				   }
				   
				   
			   }
			   return r;
			   
		        
		        
		   }

	}


发布了34 篇原创文章 · 获赞 4 · 访问量 1346

猜你喜欢

转载自blog.csdn.net/zj20165149/article/details/103935484
今日推荐