{ }codelper
목록에서 빼기P0058

같은 값 모두 빼기

첫 줄에 수의 개수 n, 둘째 줄에 정수 n개, 셋째 줄에 정수 x가 주어진다.
목록에서 x와 같은 값을 모두 빼라.
첫 줄에 남은 개수를, 둘째 줄에 남은 수를 원래 차례대로 빈칸 하나씩 띄워 출력하라.
남은 수가 없으면 첫 줄에 0을 쓰고 둘째 줄은 빈 줄로 둔다.
x가 목록에 없으면 목록은 그대로다.

입력
1 ≤ n ≤ 10,000, 모든 수와 x는 -1,000 이상 1,000 이하의 정수
출력
두 줄: 남은 개수, 남은 수들(없으면 빈 줄)
예시 1 · stdin
8
2 2 1 2 2 2 3 2
2
stdout
2
1 3
예시 2 · stdin
3
4 4 4
4
stdout
0

main.py
입력(stdin)

실행하면 이 줄들이 차례로 input()·표준 입력으로 들어가요(실행 중에 묻지 않아요).

$ 준비됐어요

코드를 입력해 풀려면 PC에서 열어 주세요. 모바일에서는 문제와 풀이를 볼 수 있어요.

다른 언어로는?언어별 풀이 보기 · 8개 언어 풀이

가장 흔한 함정은 앞에서부터 돌면서 지우기예요.
칸을 하나 지우면 뒤의 것이 한 칸씩 당겨지는데 번호는 그대로 하나 늘어나서, 붙어 있는 "2 2"의 둘째 2를 건너뛰어요.
Python for v in a: a.remove(v)도 같은 이유로 건너뜁니다.
고치는 길은 둘: 남길 것만 새 목록으로 모으거나(Python [v for v in a if v != x], JavaScript·TypeScript a.filter(v => v !== x)), 뒤에서부터 지우기.
한 번에 모두 지우는 도구: Java list.removeIf(v -> v == x), C# list.RemoveAll(v => v == x), C++20 std::erase(a, x)(그 전에는 erase-remove 관용구), C는 남길 것을 앞으로 당겨 쓰는 번호 하나.
함정 둘 더: JavaScript a.splice(a.indexOf(x), 1)은 하나만 지우고, x가 없으면 indexOf가 -1이라 맨 끝을 지워요.
Java List<Integer>의 remove(x)에 int를 넘기면 값이 아니라 x번 자리를 지웁니다(remove(Integer.valueOf(x))라야 값).
크레이콘은 뒤에서부터 a.자리빼기(i)로 지웠어요(a.빼기(x)는 하나만 지워요).

Pythonmain.py · 6 줄
n = int(input())a = list(map(int, input().split()))x = int(input())rest = [v for v in a if v != x]print(len(rest))print(*rest)
JavaScriptmain.js · 5 줄
const [n, ...rest] = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number);const a = rest.slice(0, n);const x = rest[n];const left = a.filter((v) => v !== x);console.log(left.length + "\n" + left.join(" "));
TypeScriptmain.ts · 6 줄
import { readFileSync } from "node:fs";const [n, ...rest]: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number);const a: number[] = rest.slice(0, n);const x: number = rest[n];const left: number[] = a.filter((v) => v !== x);console.log(left.length + "\n" + left.join(" "));
JavaMain.java · 19 줄
import java.util.ArrayList;import java.util.List;import java.util.Scanner;import java.util.StringJoiner; public class Main {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        int n = sc.nextInt();        List<Integer> a = new ArrayList<>();        for (int i = 0; i < n; i++) a.add(sc.nextInt());        int x = sc.nextInt();        a.removeIf(v -> v == x);        StringJoiner out = new StringJoiner(" ");        for (int v : a) out.add(String.valueOf(v));        System.out.println(a.size());        System.out.println(out);    }}
C#Main.cs · 16 줄
using System;using System.Collections.Generic;using System.Linq; class Program{    static void Main()    {        Console.ReadLine();        List<int> a = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList();        int x = int.Parse(Console.ReadLine());        a.RemoveAll(v => v == x);        Console.WriteLine(a.Count);        Console.WriteLine(string.Join(" ", a));    }}
C++main.cpp · 14 줄
#include <iostream>#include <vector> int main() {    int n, x;    std::cin >> n;    std::vector<int> a(n);    for (int& v : a) std::cin >> v;    std::cin >> x;    std::erase(a, x);  // C++20. 그 전에는 a.erase(std::remove(a.begin(), a.end(), x), a.end());    std::cout << a.size() << "\n";    for (size_t i = 0; i < a.size(); i++) std::cout << (i ? " " : "") << a[i];    std::cout << "\n";}
Cmain.c · 16 줄
#include <stdio.h> int main(void) {    static int a[10000];    int n, x, m = 0;    scanf("%d", &n);    for (int i = 0; i < n; i++) scanf("%d", &a[i]);    scanf("%d", &x);    /* 남길 것만 앞으로 당겨 쓴다: m은 다음에 쓸 자리 */    for (int i = 0; i < n; i++)        if (a[i] != x) a[m++] = a[i];    printf("%d\n", m);    for (int i = 0; i < m; i++) printf(i ? " %d" : "%d", a[i]);    putchar('\n');    return 0;}
Craykonmain.cray · 13 줄
n = 콘솔.줄읽기().수로변환();a = 콘솔.수들읽기();x = 콘솔.줄읽기().수로변환();// 뒤에서부터 지우면 지운 뒤 당겨지는 칸을 건너뛰지 않는다반복 (i = a.개수 - 1; i >= 0; i--){    만약 (a[i] == x)    {        a.자리빼기(i);    }}콘솔.쓰기(a.개수);콘솔.쓰기(a);