Categories
木有技术

LeetCode 611. Valid Triangle Number

https://leetcode.com/problems/valid-triangle-number/description/
有点类似3Sum的题目。形成三角形的充要条件是最小两边之和大于第三边。可以先给数组排序,然后确定一个最大边,然后在它左边找另外两边。
时间复杂度是O(n*log(n) + n^2) = O(n^2)

class Solution {
public:
    int triangleNumber(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int count = 0;
        for (int i = nums.size() - 1; i >= 0; --i)
        {
            // two sum (x + y) > nums[i]
            int j = 0;
            int k = i - 1;
            while (j < k)
            {
                if (nums[j] + nums[k] <= nums[i])
                {
                    j++;
                    continue;
                }
                count += (k - j);
                k--;
            }
        }
        return count;
    }
};

 
 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.