976. 三角形的最大周长『简单』

题目来源于力扣(LeetCode

一、题目

976. 三角形的最大周长

题目相关标签:排序、数学

提示:

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

二、解题思路

  1. 首先对数组进行排序

  2. 倒序遍历数组,对范围内的数组元素进行比较

  3. 判断当前遍历的元素是否小于前两位元素的和

    三角形定理:任意两条边大于第三条边

    即判断较小的两条边的和是否大于较长的一条边

三、代码实现

public static int largestPerimeter(int[] A) {
    int[] nums = A;
    // 排序操作
    Arrays.sort(nums);
    // 倒序遍历
    for (int i = nums.length - 1; i >= 2; i--) {
        int a = nums[i];
        int b = nums[i - 1];
        int c = nums[i - 2];
        // 三角形的任意两条边都大于另一条边
        if (a < b + c) {
            return a + b + c;
        }
    }
    return 0;
}

四、执行用时

五、部分测试用例

public static void main(String[] args) {
    int[] nums = {2, 1, 2};  // output: 5
//    int[] nums = {1, 2, 1};  // output: 0
//    int[] nums = {3, 2, 3, 4};  // output: 10
//    int[] nums = {3, 6, 2, 3};  // output: 8

    int result = largestPerimeter(nums);
    System.out.println(result);
}
posted @ 2020-06-23 20:28  知音12138  阅读(281)  评论(0编辑  收藏  举报