0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

LeetCode #3024. Type of Triangle

Posted at

【LeetCode #3024】Type of Triangle

問題概要

三角形を成す 3 つの数値が与えられるので,値によって下記のいずれかを返す.

  • 3 辺が全て等しい = equilateral
  • 2 辺が等しい = isosceles
  • どの辺も等しくない = scalene
  • 三角形が作れない = none

入力: nums = [3, 3, 3]
出力: "equilateral"

入力: nums = [3, 4, 5]
出力: "scalene"

カテゴリ

問題難易度:easy
タグ:Array, Math, Sorting

解法:sort をして比較を単純に

まず,三角形が作成できるかを考えます.
3 辺が与えられて三角形が作成できるのは下記を満たす場合です.
3 辺の長さをそれぞれ $a, b, c$ とすると,

\begin{align}
a + b > c  \\
a + c > b  \\
b + c > a
\end{align}

これは中学の数学で習うかと思います.
直感的には,

  • a + b <= c の場合,a と b が繋がらない
  • a + b == c の場合,ただの直線
    となるためです.

これを用いて三角形が作成できるか判定し,できる場合はさらに細かく値を見ていく方針をとります.
ここで,前述の条件を満たすかについて,sort することで 1 つの条件で判定が可能になります.
sort をすることで,nums[2] が最大になるので,下記が満たされたら他の条件も満たされることになります.

nums[0] + nums[1] > nums[2]

これを用いて実装したものが下記です.

class Solution:
    def triangleType(self, nums: List[int]) -> str:
        a, b, c = sorted(nums)
        if a + b <= c:
            return "none"
        if a == b and a == c:
            return "equilateral"
        if a == b or a == c or b == c:
            return "isosceles"
        return "scalene"

TypeScript

TypeScript では次のようになります.

function triangleType(nums: number[]): string {
    const [a, b, c] = nums.sort((a, b) => a - b);
    if (a + b <= c){
        return "none";
    }
    if ((a === b) && (a === c)){
        return "equilateral";
    }
    if ((a === b) || (a === c) || (b === c)){
        return "isosceles";
    }
    return "scalene";
};

まとめ

今回は三角形の 3 辺の長さによって返す文字列が変わる問題に挑戦しました.
簡単ですが,三角形が成り立つ条件を忘れているとちょっと困ってしまう問題だったかもしれません.
これを機に思い出しましょう!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?