My O(n^2) AC c++ code!


  • -1
    L

    class Solution {
    public:
    int threeSumClosest(vector<int> &num, int target) {
    sort(num.begin(), num.end());
    int j,k,sum, cha, m=INT_MAX, res;
    for (int i=0;i<num.size()-2;++i) {
    j = i+1;
    k = num.size()-1;
    while(j < k) {
    sum = num[i] + num[j] + num[k];
    cha = abs(sum - target);
    if (cha == 0) return sum;
    if (cha < m) {
    m = cha;
    res = sum;
    }
    if (sum < target) j++;
    else k--;
    }
    }
    return res;
    }
    };


  • 0
    L

    for (int i=0;i<num.size()-2;++i) why ++i rather than i++ here ?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.