1. 程式人生 > >[LeetCode] 016. 3Sum Closest (Medium) (C++/Java/Python)

[LeetCode] 016. 3Sum Closest (Medium) (C++/Java/Python)

016.3Sum_Closest (Medium)

連結

題意

在給定數列中找出三個數,使和最接近 target。

分析

程式碼

C++:

class Solution {
public:
	int threeSumClosest(vector<int> &num, int target) {
		int ret = num[0] + num[1] + num[2];
		int len = num.size();

		sort(num.begin(), num.end());

		for (int i = 0; i <= len - 3; i++) {
			// first number : num[i]
			int j = i + 1;	// second number
			int k = len - 1;	// third number
			while (j < k) {
				int sum = num[i] + num[j] + num[k];
				if (abs(sum - target) < abs(ret - target))
					ret = sum;
				if (sum < target) {
					++j;
				} else if (sum > target) {
					--k;
				} else {
					++j;
					--k;
				}
			}
		}
		return ret;
	}
};


Java:

public class Solution {

    public int threeSumClosest(int[] num, int target) {
        Arrays.sort(num);
        int ret = num[0] + num[1] + num[2];
        int len = num.length;
        for (int i = 0; i <= len - 3; i++) {
            // first number : num[i]
            int j = i + 1;	// second number
            int k = len - 1;	// third number
            while (j < k) {
                int sum = num[i] + num[j] + num[k];
                if (Math.abs(sum - target) < Math.abs(ret - target))
                    ret = sum;
                if (sum < target) {
                    ++j;
                } else if (sum > target) {
                    --k;
                } else {
                    ++j;
                    --k;
                }
            }
        }
        return ret;

    }
}


Python:

class Solution:
    # @return an integer
    def threeSumClosest(self, num, target):
        if not len(num):
            return 0
        ret = num[0] + num[1] + num[2]
        num.sort()
        for i in range(len(num) - 2):
            j = i + 1
            k = len(num) - 1
            while j < k:
                tsum = num[i] + num[j] + num[k]
                if abs(tsum - target) < abs(ret - target):
                    ret = tsum
                if tsum < target:
                    j += 1
                elif tsum > target:
                    k -= 1
                else:
                    j += 1
                    k -= 1
        return ret