编程语言
首页 > 编程语言> > [LeetCode] 976. Largest Perimeter Triangle (C++)

[LeetCode] 976. Largest Perimeter Triangle (C++)

作者:互联网

[LeetCode] 976. Largest Perimeter Triangle (C++)

Easy

Share
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 Solution {
public:
    int largestPerimeter(vector<int>& A) {
        // 3 <= A.length <= 10000
        int res;
        if(A.size()==3) {
            sort(A.begin(),A.end(),greater<int>());
            if(A.at(1)+A.at(2)>A.at(0)) { 
                // the sum of any two sides is greater than the third side
                return A.at(0)+A.at(1)+A.at(2);
            }
        }
        else { // the number of sides is greater than 3
            sort(A.begin(),A.end(),greater<int>());
            for(int i=0;(i+2)<A.size();i++) {
                if (A.at(i+1)+A.at(i+2)>A.at(i)) {
                    return A.at(i)+A.at(i+1)+A.at(i+2);
                }
            }
        }
        return 0; // just judge the situation that matches the problem, and the rest will return 0
    }
};


/**
 * Submission Detail:
 * Runtime: 56 ms, faster than 71.90% of C++ online submissions for Largest Perimeter Triangle.
 * Memory Usage: 10.4 MB, less than 100.00% of C++ online submissions for Largest Perimeter Triangle.
 */

标签:Perimeter,976,Triangle,return,Largest,Input,than
来源: https://blog.csdn.net/ceezyyy11/article/details/89241451