跳转至

611.Valid Triangle Number

Tags: Array

Links: https://leetcode.com/problems/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

Note:

  1. The length of the given array won't exceed 1000.
  2. The integers in the given array are in the range of [0, 1000].

class Solution {
public:
    int triangleNumber(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int res = 0;
        for (int k = nums.size() - 1; k >= 2; --k) {
            for (int i = 0; i <= k - 2; ++i) {
                for (int j = i + 1; j < k; ++j) {
                    if (nums[i] + nums[j] > nums[k]) {
                        res += k - j;
                        break;
                    }
                }
            }
        }

        return res;
    }
};

简单的模拟,和AtCoder的一道题很类似。但是这种暴力解法如果时间限制严格一点就会超时。所以考虑能否优化到O(n^2)。和题目3Sum Smaller几乎是同一种思路。时间从376ms降到12ms

class Solution {
public:
    int triangleNumber(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int res = 0, n = nums.size();
        for (int i = n - 1; i >= 2; --i) {
            int left = 0, right = i - 1;
            while (left < right) {
                if (nums[left] + nums[right] > nums[i]) {
                    res += right - left;
                    --right;
                } else {
                    ++left;
                }
            }
        }

        return res;
    }
};