(Easy) Largest Perimeter Triangle LeetCode

叁歲伎倆 2021-10-29 10:46 262阅读 0赞

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:

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

Example 2:

  1. Input: [1,2,1]
  2. Output: 0

Example 3:

  1. Input: [3,2,3,4]
  2. Output: 10

Example 4:

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

Note:

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

    class Solution {

    1. public int largestPerimeter(int[] A) {
    2. if (A.length <3){
    3. return 0;
    4. }
    5. Arrays.sort(A);
    6. int len = A.length;
    7. for(int i = len -3; i>=0;i--){
    8. if(calc(A[i],A[i+1],A[i+2])){
    9. return A[i]+A[i+1]+A[i+2];
    10. }
    11. }
    12. return 0;
    13. }
    14. public boolean calc(int a, int b , int c){
    15. if(a+b> c && a+c > b && b+c > a){
    16. return true;
    17. }
    18. else {
    19. return false;
    20. }
    21. }

    }

转载于:https://www.cnblogs.com/codingyangmao/p/11285750.html

发表评论

表情:
评论列表 (有 0 条评论,262人围观)

还没有评论,来说两句吧...

相关阅读