힘 단추 16: 가장 가 까 운 3 수의 합
1444 단어 알고리즘
포함 n 개의 정수 배열
nums
목표 치 target
。찾아내다 nums
중 세 개의 정수 로 그것들의 합 과 target
가장 가깝다.이 세 수의 합 을 되돌리다.각 조 의 입력 에 유일한 답 만 존재 한다 고 가정 하 다. , nums = [-1,2,1,-4], target = 1.
target 2. (-1 + 2 + 1 = 2).
분석:
두 개의 전역 변 수 를 사용 합 니 다. 하 나 는 threeSum 입 니 다. target 과 가장 가 까 운 세 개의 합 입 니 다.하 나 는 less 로 세 개의 수 와 target 의 최소 차 이 를 저장 합 니 다.
현재 세 개의 수의 합 과 target 의 차이 가 less 보다 적 으 면 less 대 가 를 현재 세 수의 합 과 target 의 차이 로 합 니 다. 이때 threeSum 대 가 는 현재 세 수의 합 입 니 다.
현재 세 수의 합 과 target 의 차이 가 less 보다 작 지 않 으 면 less 값 은 변 하지 않 고 threeSum 의 값 도 변 하지 않 습 니 다.
코드:
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums); //
int threeSum=nums[0]+nums[1]+nums[2];//threeSum target
int less=(threeSum>target)?(threeSum-target):(target-threeSum);//less target
for(int i=0;i<=nums.length-3;i++){
int left=i+1;
int right=nums.length-1;
while(lefttarget){
less=(s-target