zoukankan      html  css  js  c++  java
  • 3Sum Closest

       找到与target最接近的三个数的和。

    int three_sum_closest(vector<int> &num, int target) 
    {
        int result = 0;
        int dist = INT_MAX;
        
        sort(num.begin(), num.end());
        
        for (vector<int>::const_iterator it = num.begin();
            it != num.end();
            ++it)
        {
            vector<int>::const_iterator front = it + 1;
            vector<int>::const_iterator back = num.end() - 1;
            
            while (front < back)
            {
                const int sum = *it + *front + *back;
                
                if (sum < target)
                {
                    if (target - sum < dist)
                    {
                        dist = target - sum;
                        result = sum;
                    }
                    
                    ++front;
                }
                else if (sum > target)
                {
                    if (sum - target < dist)
                    {
                        dist = sum - target;
                        result = sum;
                    }
                    
                    --back;
                }
                else
                {
                    dist = 0;
                    result = target;
                    break;
                }
            }
        }
        
        return result;
    }
  • 相关阅读:
    【leetcode】修剪二叉搜索树
    053-621
    053-620
    053-619
    053-618
    053-617
    053-616
    053-615
    053-614
    053-613
  • 原文地址:https://www.cnblogs.com/codingmylife/p/2663828.html
Copyright © 2011-2022 走看看