#16 3Sum Closest

題目鏈接:https://leetcode.com/problems/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).


void Sort(int *data,int n) {<span style="white-space:pre">		</span>//歸併排序非遞歸實現
	int *tmp = (int *)malloc(n * sizeof(int));
	int lBegin, lEnd, rBegin, rEnd;
	int i,j,k;
	int len = 1;
	while (len < n) {
		lBegin = 0;
		lEnd = len - 1;
		rBegin = len;
		while (rBegin < n) {
			rEnd = lEnd + len < n - 1 ? lEnd + len : n - 1;
			i = lBegin,j = rBegin,k = lBegin;
			while (i <= lEnd && j <= rEnd) {
				if (data[i] <= data[j])
					tmp[k++] = data[i++];
				else
					tmp[k++] = data[j++];
			}
			while (i <= lEnd)
				tmp[k++] = data[i++];
			while (j <= rEnd)
				tmp[k++] = data[j++];
			for (i = lBegin; i <= rEnd; ++i)
				data[i] = tmp[i];
			lBegin += 2 * len;
			lEnd += 2 * len;
			rBegin += 2 * len;
		}
		len *= 2;
	}
	free(tmp);
}

int threeSumClosest(int* nums, int numsSize, int target) {
    int i, j, k;
    int sum, closestSum = nums[0] + nums[1] + nums[2];
    Sort(nums, numsSize);       //先排序
    for(i = 0; i < numsSize; ++i) {     //每趟一個數固定,另兩個數分別從剩下數列的第一個和最後一箇中間逼近
        j = i + 1;
        k = numsSize - 1;
        while(j < k) {
            sum = nums[i] + nums[j] + nums[k];
            if(sum < target) {          //和小於target,只有增大j才能使sum變大,從而更接近target
                if(abs(sum-target) < abs(closestSum-target))        //如果更接近target更新closetSum
                    closestSum = sum;
                ++j;
            }
            else if(sum > target) {     //和大於target,減小sum
                if(abs(sum-target) < abs(closestSum-target))
                    closestSum = sum;
                --k;
            } 
            else            //如果等於target是接近答案,直接返回結果
                return sum;
        }
    }
    return closestSum;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章