Given an array A of positive lengths, return the largest perimeter of a triangle with non-zero area, formed from 3 of these lengths.

If it is impossible to form any triangle of non-zero area, return 0.



Example 1:

Input: [2,1,2]
Output: 5
Example 2:

Input: [1,2,1]
Output: 0
Example 3:

Input: [3,2,3,4]
Output: 10
Example 4:

Input: [3,6,2,3]
Output: 8


Note:

3 <= A.length <= 10000
1 <= A[i] <= 10^6

这题提供一个数组,我们需要从数组中找出三角形的三条边,这三条边必须能组成一个三角形并且三角形的周长最长。

这题解法很直接,直接一个排序,三个三个看看能否组成三角形即可。

class LargestPerimeterTriangle : public Solution {
public:
    void Execute() {
        std::cout << "Case 1: " << largestPerimeter(vector<int>{9,2,2,9,1,1,1,2}) << std::endl;
    }

    int largestPerimeter(vector<int> A) {
        std::sort(A.rbegin(), A.rend());

        for (std::size_t i = 2; i < A.size(); i++) {
            if (A[i - 2] < A[i - 1] + A[i]) {
                return A[i - 2] + A[i - 1] + A[i];
            }
        }
        return 0;
    }
};
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day