Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Should be "Medium" or even "Easy".. Just with a little Greedy.

class Solution {
public:
    /**
     * @param S: A list of integers
     * @return: An integer
     */
    int triangleCount(vector<int> &S) {
        int n = S.size();
        if(n < 3) return 0;
        
        sort(S.begin(), S.end());
        int ret = 0;
        
        for(int e = n - 1; e > 1; e --)
        {
            int s = 0, m = e - 1;
            while(s < m)
            {
                if( (S[s] + S[m]) <= S[e])
                {
                    s ++;
                }
                else
                {
                    ret += m - s;
                    m --;
                }
            }
        }
        
        return ret;
    }
};
posted on 2015-10-21 07:53  Tonix  阅读(254)  评论(0编辑  收藏  举报