611. Valid Triangle Number

Given an array consists of non-negative integers, your task is to count the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.

Example 1:

Input: [2,2,3,4]
Output: 3
Explanation:
Valid combinations are: 
2,3,4 (using the first 2)
2,3,4 (using the second 2)
2,2,3
class Solution {
public:
    int triangleNumber(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        int count = 0;
        for(int j = nums.size()-1;j>=2;j--)
        {
            int third = nums[j];
            int left = 0, right = j-1;
            while(left<right) 
            {
                if((nums[left]+nums[right])>third)
                {
                    count+= right-left;
                    right--;
                }
                else
                    left++;
            }
            
        }
        return count;
    }
};

 

posted @ 2017-12-22 15:39  jxr041100  阅读(180)  评论(0编辑  收藏  举报