oj赛氪算法练习

开关灯2

oj赛氪算法练习_第1张图片

import java.util.ArrayList;
import java.util.Scanner;

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

        ArrayList result = findClosedLamps(N);

        // 输出结果
        for (int i : result) {
            System.out.print(i + " ");
        }
    }

    private static ArrayList findClosedLamps(int N) {
        ArrayList closedLamps = new ArrayList<>();

        // 初始化数组,全部设置为 true 表示灯都是开着的
        boolean[] lamps = new boolean[N + 1];

        // 开关灯操作
        for (int i = 2; i <= N; i++) {
            for (int j = i; j <= N; j += i) {
                lamps[j] = !lamps[j];
            }
        }

        // 找到关闭的灯的编号
        for (int i = 1; i <= N; i++) {
            if (!lamps[i]) {
                closedLamps.add(i);
            }
        }

        return closedLamps;
    }
}

你可能感兴趣的:(算法练习,算法,java,开发语言)