Skip to content

Files

Latest commit

5054c79 ยท Dec 21, 2020

History

History
42 lines (30 loc) ยท 1.44 KB

README.md

File metadata and controls

42 lines (30 loc) ยท 1.44 KB

[baekjoon-14425] ๋ฌธ์ž์—ด ์ง‘ํ•ฉ

image

๋” ํšจ์œจ์ ์ธ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ƒ๊ฐํ•˜๊ธฐ

๋ณธ ๋ฌธ์ œ๋Š” ๋Œ€์ƒ ๋ฌธ์ž์—ด์ด ๋ฌธ์ž์—ด ์ง‘ํ•ฉ ๋‚ด์— ์žˆ๋Š”์ง€ ์ผ์ผ์ด ๊ฒ€์‚ฌํ•ด๋ณด๋Š” ์ˆ˜๋ฐ–์— ์—†๋‹ค.

์ฒ˜์Œ์—๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์ด O(N*M) ์œผ๋กœ ํ’€์—ˆ๋‹ค. ์‹œ๊ฐ„ ์ œํ•œ์ด 2์ดˆ์ด๊ณ , N๊ณผ M์˜ ์ตœ๋Œ“๊ฐ’์€ 10000์ด๊ธฐ ๋•Œ๋ฌธ์— ๋ฌธ์ œ ์—†์—ˆ๋‹ค.

String S = new String[N];
for (int i = 0; i < N; i++) S[i] = br.readLine();

int ans = 0;
for (int i = 0; i < M; i++) {
    String s = br.readLine();
    for (int j = 0; j < N; j++) {
        if (s.equals(S[j])) ans ++;
    }
}

์ด ๋•Œ ๋‹ต์€ ๋งž์•˜์œผ๋‚˜ ์‹œ๊ฐ„ ํšจ์œจ์ด ์ข‹์ง€ ์•Š์€ ๊ฒƒ ๊ฐ™์•„ ๋‹ค๋ฅธ ์ฝ”๋“œ๋ฅผ ์ฐธ๊ณ ํ•˜์˜€๊ณ , Java Collections์˜ HashSet์„ ์ด์šฉํ•˜๋ฉด ์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ํฌ๊ฒŒ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค๋Š” ๊ฒƒ์„ ์•Œ๊ฒŒ ๋˜์—ˆ๋‹ค.

HashSet์˜ Add, Contains ์—ฐ์‚ฐ์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” ๋ชจ๋‘ O(1) ์ด๋‹ค. ๋”ฐ๋ผ์„œ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜๋ฉด ๋” ์ข‹์€ ์ฝ”๋“œ๊ฐ€ ๋  ์ˆ˜ ์žˆ๊ฒ ์ง€ !!

HashSet<String> hs = new HashSet<>();
while (N-- > 0) hs.add(br.readLine());

int ans = 0;
for (int i = 0; i < M; i++)
    if (hs.contains(br.readLine())) ans ++;

image

์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ 2648ms ์—์„œ 424ms๋กœ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค.