976. Largest Perimeter Triangle

Easy
​
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

解法

三角形成立條件為:任意兩邊長度相加皆大於第三邊
進行排序後,取最大的比較是否小於第二大、第三大的數字,若小於的話即符合構成三角形的條件。
func largestPerimeter(nums []int) int {
sort.Ints(nums)
​
for i := len(nums) - 1; i >= 2; i-- {
if nums[i] < nums[i-1]+nums[i-2] {
return nums[i] + nums[i-1] + nums[i-2]
}
}
​
return 0
}