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.
今天又是三角形了!每日一題好像每週會相關?下週再觀察一下是不是真的有規律😅
3 <= nums.length <= 104
1 <= nums[i] <= 106
Input: nums = [2,1,2]
Output: 5
Explanation: You can form a triangle with three side lengths: 1, 2, and 2.
class Solution {
public:
int largestPerimeter(vector<int>& nums) {
if(nums.size() < 3) return 0;
sort(nums.begin(), nums.end());
int n = nums.size() - 1;
// 從最大的三個數開始檢查,往前遍歷
for(int i = n; i >= 2; i--) {
// 檢查 nums[i-2], nums[i-1], nums[i] 是否能組成三角形
// 由於陣列已排序,只需檢查 nums[i-2] + nums[i-1] > nums[i]
if(nums[i-2] + nums[i-1] > nums[i]) {
return nums[i-2] + nums[i-1] + nums[i];
}
}
return 0;
}
};
略
sort(nums.begin(), nums.end())
ps. 部分內容經 AI 協助整理