zoukankan      html  css  js  c++  java
  • LeetCode 976. Largest Perimeter Triangle (三角形的最大周长)

    题目标签:Array

      题目给了我们一个 边长的 array, 让我们找出 最大边长和的三角形,当然前提得是这三条边能组成三角形。如果array 里得边长组成不了三角形,返回0。

           最直接的理解就是,找到三条最长的边,再判断是不是能够组成三角形,如果不行,继续去找更小得边。

           所以维护三个max1,max2,max3,然后利用 “任意两边之和大于第三边” 来判断。

           具体看code。

    Java Solution:

    Runtime beats 99.57% 

    完成日期:2/11/2019

    关键点:“任意两边之和大于第三边”

     1 class Solution 
     2 {
     3     public int largestPerimeter(int[] A) 
     4     {
     5         int max1 = -1;
     6         int max2 = -1;
     7         int max3 = -1;
     8         boolean triangleFormed = false;
     9         int prevMax = Integer.MAX_VALUE;
    10         
    11         do {
    12             max1 = -1;
    13             max2 = -1;
    14             max3 = -1;
    15             // iterate A to get 3 max numbers
    16             for(int max : A)
    17             {
    18                 if(max > max1 && max < prevMax)
    19                 {
    20                     max3 = max2;
    21                     max2 = max1;
    22                     max1 = max;
    23                 }
    24                 else if(max > max2 && max < prevMax)
    25                 {
    26                     max3 = max2;
    27                     max2 = max;
    28                 }
    29                 else if(max > max3 && max < prevMax)
    30                 {
    31                     max3 = max;
    32                 }
    33             }
    34 
    35             // validate 3 numbers can form triangle
    36             triangleFormed = validateTriangle(max1, max2, max3);
    37             
    38             if(!triangleFormed)
    39                 prevMax = max1;
    40             
    41             if(max1 < 0 || max2 < 0 || max3 < 0)
    42                 return 0;
    43             
    44         } while(!triangleFormed);
    45         
    46         
    47         return max1 + max2 + max3;
    48     }
    49     
    50     
    51     private boolean validateTriangle(int a, int b, int c)
    52     {
    53         if(a + b <= c)
    54             return false;
    55         else if(b + c <= a)
    56             return false;
    57         else if(c + a <= b)
    58             return false;
    59         
    60         
    61         return true;
    62     }
    63 }

    参考资料:N/A

    LeetCode 题目列表 - LeetCode Questions List

    题目来源:https://leetcode.com/

  • 相关阅读:
    第十二章学习笔记
    UVa OJ 107 The Cat in the Hat (戴帽子的猫)
    UVa OJ 123 Searching Quickly (快速查找)
    UVa OJ 119 Greedy Gift Givers (贪婪的送礼者)
    UVa OJ 113 Power of Cryptography (密文的乘方)
    UVa OJ 112 Tree Summing (树的求和)
    UVa OJ 641 Do the Untwist (解密工作)
    UVa OJ 105 The Skyline Problem (地平线问题)
    UVa OJ 100 The 3n + 1 problem (3n + 1问题)
    UVa OJ 121 Pipe Fitters (装管子)
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/10468684.html
Copyright © 2011-2022 走看看