🐡

LeetCode 1431. Kids With the Greatest Number of Candies - 各言語でのfor ループ

に公開

1431. Kids With the Greatest Number of Candies

https://leetcode.com/problems/kids-with-the-greatest-number-of-candies

Instituion

概要: キャンディ配列[1,2,3]に対して、余分なキャンディx個を足してキャンディ配列の中でもっとも大きい値になる場合はtrueとする。

  • キャンディ配列に対して最も大きい値を取る
  • キャンディ配列に対してループ処理で余分なキャンディx個を足せば良い

ruby

  • 簡単な問題だったので一回で回答完了
def kids_with_candies(candies, extra_candies)
    max = candies.max
    candies.map do |c|
      c + extra_candies >= max
    end
end
  • Time Complexity: O(n)
    • candies のすべての要素を一度見て、最大値を特定。この処理にかかる時間は、配列の要素数 n に比例するため。map処理も同様。
  • Space Complexity: O(n)
    • mapメソッドによって生成される元の配列と同じサイズの新しい配列を作成し、その中に結果を格納。この新しい配列のサイズは元の配列 candies の要素数 n と同じであるため、O(n) の追加メモリが必要

Approach

同じ手法で各言語で実装した。

python

class Solution:
    def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
        maxC = max(candies)
        results = []
        for c in candies:
            results.append(c + extraCandies >= maxC)
        return results

forループの違い:

  • for c in candies:: リストの要素そのものに必要なときに使う。
  • for i in range(len(candies)):: リストのインデックスが必要なときに使う。

内包表記で書くこともできる。

class Solution:
    def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
        maxC = max(candies)
        return [c+extraCandies >= maxC for c in candies]

typescript

function kidsWithCandies(candies: number[], extraCandies: number): boolean[] {
  const max: number = Math.max(...candies);
  const results: boolean[] = [];
  for (const c of candies){
    results.push(c + extraCandies >= max)
  }
  return results
};
  • スプレッド構文
    • Math.max() のように、複数の引数を取る関数に配列の中身を渡すことができる
const numbers = [1, 5, 2, 8];
const maxNumber = Math.max(...numbers); // maxNumber は 8
  • map記法で短く書くこともできる。
function kidsWithCandies(candies: number[], extraCandies: number): boolean[] {
  const max: number = Math.max(...candies);
  return candies.map(candy => candy + extraCandies >= max)
};

golang

スライス 配列
構文 []型 [長さ]型
[]int [5]int
長さ 可変長 固定長
func kidsWithCandies(candies []int, extraCandies int) []bool {
    maxC := slices.Max(candies)
    results := make([]bool, len(candies))

    for i, c := range(candies) {
        results[i] = c + extraCandies >= maxC
    }
    return results
}

学習のポイント

  • 各言語のforループまたはイテレータ処理について
  • golangでの最大値取得は、スライスの場合はではslicesパッケージのmax関数を使う。可変長引数の場合は、組み込み関数のmax関数を使う。

Discussion