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?

【Swift】Set()とsortedの併用で200Byte切り | 085-B: KagamiMochi【AtCoder】

0
Last updated at Posted at 2025-12-03

コード

  • 自力ACしたコードを使用。
import Foundation

let N = Int(readLine()!)!
var ds: [Int] = []

for i in 0 ..< N {
    let d = Int(readLine()!)!
    ds.append(d)
}

ds = Set(ds).sorted(by: {$0<$1})

print(ds.count)

必要な変数

  • N ... 鏡餅の個数
  • ds ... 入力された餅の直径を格納する配列(重複あり)
  • Set(ds) ... 重複を排除した集合
  • sorted ... 集合を昇順に整列させる処理
  • ds.count ... 重複を取り除いた後の個数(答え)

実装方針

1. 変数の定義

入力を受け取り、直径を格納する配列を準備する。

let N = Int(readLine()!)!
var ds: [Int] = []

for _ in 0 ..< N {
    let d = Int(readLine()!)!
    ds.append(d)
}

1-1. Point

  • 配列 ds に全ての値を入れてから重複除去を行う。
  • ループ変数 i を使用しないため _ で省略可能。

2. 重複除去と整列. 交互に値を取り合う

2-1. Set で重複を除去し、sorted で昇順に並べ替える

ds = Set(ds).sorted(by: {$0 < $1})

2-2. Point

  • Set に変換することで 重複が自動的に除去 される
  • その後 sorted によって 小さい順に整列 される
  • 実際は昇順・降順どちらでもよいが、問題では「重複を除いた個数」だけが必要

2-3. 出力

print(ds.count)

謝辞

0
0
1

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?