LoginSignup
1
0

Javaの解答例:ABC085B - Kagami Mochi , AtCoder Beginners Selection

Last updated at Posted at 2024-03-23

はじめに

自分用の備忘録です。参考になれば。

問題文

以下のリンクを参考にしてください。
ABC085B - Kagami Mochi, https://atcoder.jp/contests/abs/tasks/abc085_b

解答例 自作

Main.java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int N = sc.nextInt();
        List<Integer> D = new ArrayList<Integer>();
        for (int i = 1; i <= N; i++) {
            D.add(sc.nextInt());
        }

        List<Integer> hashD = new ArrayList<>(new HashSet<>(D));
        System.out.println(hashD.size());
    }

}

公式の解答1をJavaに変換

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int N = scanner.nextInt();
        int[] d = new int[N];
        for (int i = 0; i < N; ++i) d[i] = scanner.nextInt();

        int[] num = new int[110];  // バケット
        for (int i = 0; i < N; ++i) {
            num[d[i]]++;  // d[i] が 1 個増える
        }

        int res = 0;  // 答えを格納
        for (int i = 1; i <= 100; ++i) {  // 1 <= d[i] <= 100 なので 1 から 100 まで探索
            if (num[i] > 0) {  // 0 より大きかったら
                ++res;
            }
        }
        System.out.println(res);
    }
}

公式の解答2をJavaに変換

import java.util.Scanner;
import java.util.HashSet;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int N = scanner.nextInt();
        int[] d = new int[N];
        for (int i = 0; i < N; ++i) d[i] = scanner.nextInt();

        HashSet<Integer> values = new HashSet<>(); // insert するときに重複を取り除いてくれます
        for (int i = 0; i < N; ++i) {
            values.add(d[i]); // 挿入します
        }

        // set のサイズを出力します
        System.out.println(values.size());
    }
}

参考文献

https://qiita.com/drken/items/fd4e5e3630d0f5859067#%E7%AC%AC-7-%E5%95%8F--abc-085-b---kagami-mochi-200-%E7%82%B9
https://codingls.com/java/773/

1
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
1
0