はじめに
ポイント
- for文とif文を使う
この記事で得られること
- for文の基本的な使い方
- if文の基本的な使い方
この記事が役立ちそうな方
- プログラミング初心者
- Python初心者
- for文とif文を使いこなしたい方
詳細
問題
原文
A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.
Given an array of numbers
arr
, returntrue
if the array can be rearranged to form an arithmetic progression. Otherwise, returnfalse
.
Example 1:
123 Input: arr = [3,5,1]Output: trueExplanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.Example 2:
123 Input: arr = [1,2,4]Output: falseExplanation: There is no way to reorder the elements to obtain an arithmetic progression.
Constraints:
2 <= arr.length <= 1000
-106 <= arr[i] <= 106
内容(和訳)
ある連続する数字の並び(数列)は、もし全ての連続する要素の差が同じだった場合、等差数列と呼ばれます。
数字の配列arrが与えられるので、等差数列として並べ替えられる場合はTrueを返してください。
そうでない場合はFalseを返してください。
※正しくない可能性があります。
解答
解答1:Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Solution: def canMakeArithmeticProgression(self, arr: List[int]) -> bool: #arrをソート。何も指定しなければ昇順になる arr.sort() #2つ目の要素 - 1つ目の要素の値を変数differnceに入れる difference = arr[1] - arr[0] #for文で2番目の要素から最後まで走査する for i in range(1,len(arr)): #i番目の要素 - (i-1)番目の要素がdiffernceと異なる場合 if arr[i] - arr[i-1] != difference: #Falseを返す return False #全ての差が同じで、for文のループが最後まで完了したときはTrueを返す。 return True |
解答2:Python, 英語でコメント
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Solution: def canMakeArithmeticProgression(self, arr: List[int]) -> bool: #sort arr in ascending order. arr.sort() #store difference by subtract between 1st element and 2nd elment of arr. difference = arr[1] - arr[0] #traverse each element of arr from 2nd to last. for i in range(1,len(arr)): #if subtract between i-th and [i-1]-th element is not equal difference if arr[i] - arr[i-1] != difference: # return False return False # if differences between any two consective elements is the same (and finish traversing of arr). # return True return True |
コードは解答1と同じです。
実際の面接では英語で話しながらになりますが、
いきなり英語で話しながら解答することはできないので、
まずは時間かけて考えられる、英語でコメントを書きながら解答を作る作業をしてみます。
終わりに
補足・参考・感想
問題を分類しました。テーマごとに集中して問題を解くことができます。
LeeetCodeの問題をアルゴリズムとデータ構造による分類
LeetCodeに特有の内容など、知っておくと役に立つかもしれないことをまとめました。
疑問が解決した方はこちらへ
前:1822. Sign of the Product of an Array
次:589. N-ary Tree Preorder Traversal
疑問が解決しない方はこちらへ
if文の基本的な使い方をおさらいしたい方はこの記事へどうぞ
for文の基本的な使い方をおさらいしたい方はこの記事へどうぞ
コメント