976. Largest Perimeter Triangle
Дан 정수 배열 nums. return наибольший периметр треугольника с ненулевой площадью, образованный из трех этих длин. Если невозможно образовать треугольник с ненулевой площадью, return 0.
예제:
Input: nums = [1,2,1,10]
Output: 0
Explanation:
You cannot use the side lengths 1, 1, and 2 to form a triangle.
You cannot use the side lengths 1, 1, and 10 to form a triangle.
You cannot use the side lengths 1, 2, and 10 to form a triangle.
As we cannot use any three side lengths to form a triangle of non-zero area, we return 0.
C# 해법
매칭됨/원본public class Solution {
public int LargestPerimeter(int[] A) {
Array.Sort(A);
for (int i = A.Length - 3; i >= 0; --i)
if (A[i] + A[i + 1] > A[i + 2])
return A[i] + A[i + 1] + A[i + 2];
return 0;
}
}
C++ 해법
자동 초안, 제출 전 검토#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
public int LargestPerimeter(vector<int>& A) {
sort(A.begin(), A.end());
for (int i = A.size() - 3; i >= 0; --i)
if (A[i] + A[i + 1] > A[i + 2])
return A[i] + A[i + 1] + A[i + 2];
return 0;
}
}
Java 해법
자동 초안, 제출 전 검토import java.util.*;
import java.math.*;
// Auto-generated Java draft from the C# solution. Review API differences before LeetCode submit.
public class Solution {
public int LargestPerimeter(int[] A) {
Arrays.sort(A);
for (int i = A.length - 3; i >= 0; --i)
if (A[i] + A[i + 1] > A[i + 2])
return A[i] + A[i + 1] + A[i + 2];
return 0;
}
}
JavaScript 해법
매칭됨/원본var largestPerimeter = function(A) {
A.sort((a, b) => a - b);
for (let i = A.length - 3; i >= 0; --i)
if (A[i] + A[i + 1] > A[i + 2])
return A[i] + A[i + 1] + A[i + 2];
return 0;
};
Python 해법
매칭됨/원본class Solution:
def largestPerimeter(self, A: List[int]) -> int:
A.sort()
for i in range(len(A) - 3, -1, -1):
if A[i] + A[i + 1] > A[i + 2]:
return A[i] + A[i + 1] + A[i + 2]
return 0
Algorithm
Отсортируйте 배열 nums в порядке возрастания.
Для каждого elementа c в 배열е, начиная с конца: Выберите два наибольших возможных значения a и b, которые находятся перед c в отсортированном 배열е (т.е. значения, смежные с c). Проверьте, образуют ли a, b и c треугольник (문제 설명 треугольника: a + b > c). Если образуют, return их сумму как периметр треугольника.
Если не удалось find такие значения, return 0.
😎
Vacancies for this task
활성 채용 with overlapping task tags are 표시됨.