겹치는 수 지우기
첫 줄에 정수의 개수 n, 둘째 줄에 정수 n개가 주어진다.
앞에서 이미 나온 값은 지우고, 처음 나온 차례 그대로 남은 값을 빈칸 하나로 띄워 한 줄에 출력하라(3 1 3 2 1이면 3 1 2).
- 입력
- 1 ≤ n ≤ 1000, -1,000,000,000 ≤ 각 정수 ≤ 1,000,000,000
- 출력
- 겹침을 지운 목록 한 줄
5 3 1 3 2 1
3 1 2
첫 줄에 정수의 개수 n, 둘째 줄에 정수 n개가 주어진다.
앞에서 이미 나온 값은 지우고, 처음 나온 차례 그대로 남은 값을 빈칸 하나로 띄워 한 줄에 출력하라(3 1 3 2 1이면 3 1 2).
5 3 1 3 2 1
3 1 2
실행하면 이 줄들이 차례로 input()·표준 입력으로 들어가요(실행 중에 묻지 않아요).
$ 준비됐어요
코드를 입력해 풀려면 PC에서 열어 주세요. 모바일에서는 문제와 풀이를 볼 수 있어요.
집합은 "봤나"를 빨리 알려 주지만, 차례를 지키는지는 언어마다 달라요.
Python set·C# HashSet·C++ unordered_set은 차례가 정해져 있지 않고, C++ std::set은 크기 순이에요.
그래서 집합은 확인에만 쓰고 결과는 목록에 따로 넣어요(C# if (seen.Add(x)), C++ seen.insert(x).second).
차례를 지키는 집합도 있어요: JS new Set, Java LinkedHashSet, Python dict.fromkeys(a).
C에는 집합이 없어서 지금까지 넣은 값을 처음부터 찾아요(n이 1000이면 충분히 빨라요).
크레이콘은 사전()의 있나로 확인하고 result.넣기(x)로 모아요.
n = int(input())seen = set()result = []for x in input().split(): if x not in seen: seen.add(x) result.append(x)print(" ".join(result))const [n, ...a] = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number);console.log([...new Set(a)].join(" "));import { readFileSync } from "node:fs";const [n, ...a]: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number);console.log([...new Set<number>(a)].join(" "));import java.util.LinkedHashSet;import java.util.Scanner;import java.util.Set;import java.util.StringJoiner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); Set<Integer> seen = new LinkedHashSet<>(); for (int i = 0; i < n; i++) seen.add(sc.nextInt()); StringJoiner out = new StringJoiner(" "); for (int x : seen) out.add(String.valueOf(x)); System.out.println(out); }}using System;using System.Collections.Generic; class Program{ static void Main() { Console.ReadLine(); var seen = new HashSet<int>(); var result = new List<int>(); foreach (string s in Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries)) { int x = int.Parse(s); if (seen.Add(x)) result.Add(x); } Console.WriteLine(string.Join(" ", result)); }}#include <iostream>#include <unordered_set>#include <vector> int main() { int n, x; std::cin >> n; std::unordered_set<int> seen; std::vector<int> result; for (int i = 0; i < n; i++) { std::cin >> x; if (seen.insert(x).second) result.push_back(x); } for (size_t i = 0; i < result.size(); i++) std::cout << (i ? " " : "") << result[i]; std::cout << "\n";}#include <stdio.h> int main(void) { int n, x, result[1000], m = 0; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &x); int found = 0; for (int j = 0; j < m && !found; j++) if (result[j] == x) found = 1; if (!found) result[m++] = x; } for (int i = 0; i < m; i++) printf(i ? " %d" : "%d", result[i]); putchar('\n'); return 0;}n = 콘솔.줄읽기().수로변환();a = 콘솔.수들읽기();seen = 사전();result = [];각각 (x 에서 a){ 만약 (!seen.있나(x)) { seen[x] = 참; result.넣기(x); }}콘솔.쓰기(result);