leetcode-976-easy

Largest Perimeter Triangle

Given an integer array nums, return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0.

Example 1:

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

Input: nums = [1,2,1]
Output: 0
Constraints:

3 <= nums.length <= 104
1 <= nums[i] <= 106

思路一:思路一开始就想歪了,这题的关键在于数组排序后 a <= b <= c,三角形成立的三个判断条件(两边之和大于第三边),只剩下一个 (a+b) > c,排序后其他两个条件已经默认成立了 (a+c) > b, (b+c) > a

public int largestPerimeter(int[] nums) {

    Arrays.sort(nums);
    for (int i = nums.length - 1; i >= 2; i--) {
        if (nums[i-2] + nums[i-1] > nums[i]) return nums[i - 2] + nums[i - 1] + nums[i];
    }
    
    return 0;
}
posted @ 2022-10-28 17:05  iyiluo  阅读(31)  评论(0)    收藏  举报