[Python ์ฝํ ์ ๋ฌธ] 3. (๋ฌธ์ 1๋ฒ) ๋น๋์(ver 1)
by Hi.Claire๐ฅ๏ธ ์ ๋ฌธ์๋ฅผ ์ํ ์ฝ๋ฉํ ์คํธ ํต์ฌ - Python (๊นํ์, ์ธํ๋ฐ)
์น์ 3. ํด์(Hash)
(๋ฌธ์ 1๋ฒ) ๋น๋์(ver 1)
๋งค๊ฐ๋ณ์ nums์ ๊ธธ์ด๊ฐ n์ธ ์์ด์ด ์ฃผ์ด์ง๋ฉด ์์ด์ ์์์ค์์ ๋น๋์๊ฐ 1์ธ ๊ฐ์ฅ ํฐ ์ซ์๋ฅผ ๋ฐํํ๋ ํ๋ก๊ทธ๋จ์ ์์ฑํ์ธ์.
๋น๋์ 1์ธ ์ซ์๊ฐ ์์ ๊ฒฝ์ฐ -1์ ๋ฐํํ์ธ์.
์ ์ถ๋ ฅ ์
nums | answer |
[3, 9, 2, 12, 9, 12, 8, 7, 9, 12] | 8 |
[2, 1, 3, 2, 1, 3, 4, 5, 4, 5, 6, 7, 6, 7, 8, 8] | -1 |
[23, 56, 11, 67, 120, 560, 812, 960, 560, 777, 888, 960] | 888 |
[11, 73, 156, 789, 345, 156, 789, 345, 678, 555, 678] | 555 |
[1, 3, 1, 5, 7, 2, 3, 1, 5] | 7 |
์ ํ์ฌํญ
- nums์ ๊ธธ์ด : 3 <= n <= 10,000
- ๋ฐฐ์ด nums์ ์์๋ ์์ฐ์์ ๋๋ค. 1 <= nums[i] <= 1,000
ํ์ด
def solution(nums):
answer = -1
dict1 = {}
dict2 = []
for num in nums:
if num in dict1:
dict1[num] += 1
else:
dict1[num] = 1
for key, val in dict1.items():
if val == 1:
dict2.append(key)
if len(dict2) == 0:
return answer;
else:
return max(dict2);
print(solution([3, 9, 2, 12, 9, 12, 8, 7, 9, 12]));
print(solution([2, 1, 3, 2, 1, 3, 4, 5, 4, 5, 6, 7, 6 ,7, 8, 8]));
print(solution([23, 56, 11, 67, 120, 560, 812, 960, 560, 777, 888, 960]));
print(solution([11, 73, 156, 789, 345, 156, 789, 345, 678, 555, 678]));
print(solution([1, 3, 1, 5, 7, 2, 3, 1, 5]));
8
-1
888
555
7
์ ๋ต ํ์ด
๋ถ์
๋๋ฒ์งธ ์ ํ์ฌํญ์ ๋ณด๋ฉด ๋ฐฐ์ด nums์ ์์์ ์ต๋๊ฐ์ 1000์ด๋ค.
์ด๋ฐ ๊ฒฝ์ฐ์๋ direct address table ๋ฐฉ์์ ์ฌ์ฉํ๋ ๊ฒ์ด hash table์ ์ฌ์ฉํ๋ ๊ฒ๋ณด๋ค ์๋๊ฐ ๋น ๋ฅผ ๊ฒ์ด๋ผ๊ณ ํ๋จํ ์ ์๋ค.
๋ฐฐ์ด์ ์ต๋ ๊ธธ์ด๊ฐ 1000๋ฐ์ ์ ๋๋ฏ๋ก ๋ฐฐ์ด์ ์ธ๋ฑ์ค๋ฅผ ํค๋ก ์ฌ์ฉํ์ฌ ๋น๋์๋ฅผ ์ฐพ๋ ๋ฐฉ์(๋ฐฐ์ด์ ์ธ๋ฑ์ฑ์ ์๊ฐ๋ณต์ก๋๋ O(1)์ด๋ค.)์ ๊ฐ๋จํ๋ค.
๋ฐ๋ฉดhash table(ํ์ด์ฌ์ dictionary)์ hash ํจ์๋ฅผ ์ฌ์ฉํ์ฌ hash ๊ฐ์ key, value(๋น๋์)๋ฅผ ์ ์ฅํ๋ ๋ฐฉ์์ด๋ฏ๋ก ํด๋น ์ซ์์ ๋น๋์๋ฅผ ์ฐพ์๊ฐ๋ ๋ฐฉ์์ด ๋ฐฐ์ด์ indexing์ ๋นํด ์ข ๋ ๋ณต์กํ๋ค.
๋ฐ๋ผ์ ์ด ๋ฌธ์ ๋ direct address table ๋ฐฉ์์ผ๋ก ํ์ดํ๋ค.
ํ์ด
def solution(nums):
answer = -1
# index๋ฅผ 1000๊น์ง ๊ฐ์ง๋ direct address table ์์ฑ
cnt = [0] * 1001
# ์
๋ ฅ๋ ์์ด์ ์ซ์์ ์ผ์นํ๋ ๋ฐฐ์ด์ ์ธ๋ฑ์ค ๊ฐ์ ๋น๋์ ์ถ๊ฐ
for num in nums:
cnt[num] += 1
# ๋น๋์๊ฐ 1์ธ ์ต๋๊ฐ์ ์ฐพ๊ธฐ ์ํด ๋ฐฐ์ด์ ๊ฑฐ๊พธ๋ก ์์ฐจํ์ํ๋ฉฐ ๋น๋์๊ฐ 1์ธ ๊ฐ์ ์ฐพ์ผ๋ฉด ํด๋น ์ธ๋ฑ์ค๋ฅผ ๋ฐํํ๋ค.
for i in range(1000, 0, -1):
if cnt[i] == 1:
return i;
return answer;
print(solution([3, 9, 2, 12, 9, 12, 8, 7, 9, 12]));
print(solution([2, 1, 3, 2, 1, 3, 4, 5, 4, 5, 6, 7, 6 ,7, 8, 8]));
print(solution([23, 56, 11, 67, 120, 560, 812, 960, 560, 777, 888, 960]));
print(solution([11, 73, 156, 789, 345, 156, 789, 345, 678, 555, 678]));
print(solution([1, 3, 1, 5, 7, 2, 3, 1, 5]));
8
-1
888
555
7
'๐ ์ฝ๋ฉํ ์คํธ > ์ ๋ฌธ์๋ฅผ ์ํ ์ฝ๋ฉํ ์คํธ ํต์ฌ - Python' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Python ์ฝํ ์ ๋ฌธ] 3. (๋ฌธ์ 3๋ฒ) ์๊ธฐ ๋ถ์ด์ (0) | 2024.09.01 |
---|---|
[Python ์ฝํ ์ ๋ฌธ] 3. (๋ฌธ์ 2๋ฒ) ๋น๋์(ver 2) (0) | 2024.08.31 |
[Python ์ฝํ ์ ๋ฌธ] 3. ํด์(Hash) (0) | 2024.06.27 |
[Python ์ฝํ ์ ๋ฌธ] 2. (๋ฐฑ์ค) 17608๋ฒ: ๋ง๋๊ธฐ (0) | 2024.06.09 |
[Python ์ฝํ ์ ๋ฌธ] 2. (๋ฌธ์ 6๋ฒ) ๋ ์์ ํฉ (0) | 2024.06.01 |
๋ธ๋ก๊ทธ์ ์ ๋ณด
Claire's Study Note
Hi.Claire