๐ฏ ์ด๋ณด์์ฉ ๊ฐ์ด๋ 'N-Repeated Element in Size 2N Array' โ LeetCode 961 (C++ | Python | JavaScript)
Source: Dev.to
Problem Description
๊ธธ์ด๊ฐ 2N์ธ ๋ฐฐ์ด nums๊ฐ ์ฃผ์ด์ง๋๋ค.
๋ฐฐ์ด์๋ N + 1๊ฐ์ ๊ณ ์ ํ ์์๊ฐ ์์ผ๋ฉฐ, ๊ทธ ์ค ์ ํํ ํ๋์ ์์๊ฐ N๋ฒ ๋ํ๋ฉ๋๋ค.
๋ชฉํ: N๋ฒ ๋ฐ๋ณต๋๋ ์์๋ฅผ ์ฐพ์ ๋ฐํํฉ๋๋ค.
Solution Overview
๋ฐ๋ณต๋๋ ์์๊ฐ ๋ฐฐ์ด ์ ๋ฐ์ ์ฐจ์งํ๋ฏ๋ก, ๋ ๋ฒ ๋ํ๋๋ ์์น๋ ์ต๋ ๋ ์ธ๋ฑ์ค ์ฐจ์ด๊ฐ ๋ฉ๋๋ค.
ํฌ๊ธฐโฏ3์ ์ฌ๋ผ์ด๋ฉ ์๋์ฐ๋ก ๋ฐฐ์ด์ ์ค์บํ๋ฉด, ๋ง์ง๋ง ๋ฐฐ์ด ์์์ธ ๊ฒฝ์ฐ๋ฅผ ์ ์ธํ๊ณ ๋ ์ค๋ณต์ ๋ฐ๋์ ๋ง๋๊ฒ ๋ฉ๋๋ค.
์๊ณ ๋ฆฌ์ฆ์ O(N) ์๊ฐ์ ์คํ๋๊ณ O(1) ์ถ๊ฐ ๊ณต๊ฐ์ ์ฌ์ฉํฉ๋๋ค.
C++ Implementation
class Solution {
public:
int repeatedNTimes(vector& nums) {
// Check windows of size 2 and size 3
for (int i = 0; i + 2 int:
Python Implementation
# Iterate through the list looking at neighbors
for i in range(len(nums) - 2):
if nums[i] == nums[i + 1] or nums[i] == nums[i + 2]:
return nums[i]
# If the repeat isn't within a distance of 2, it's the last element
return nums[-1]
JavaScript Implementation
/**
* @param {number[]} nums
* @return {number}
*/
var repeatedNTimes = function(nums) {
// Loop through the array checking nearby elements
for (let i = 0; i < nums.length - 2; i++) {
if (nums[i] === nums[i + 1] || nums[i] === nums[i + 2]) {
return nums[i];
}
}
// Return the last element if no match was found in the loop
return nums[nums.length - 1];
};
Key Insights
- Window Strategy: ์ธ์ ํ ์ด์(๊ฑฐ๋ฆฌโฏโคโฏ2)๋ง ํ์ธํ๋ฉด
2N๋ฐฐ์ด์์ ๋ฐ๋ณต๋๋ ์์๋ฅผ ์ฐพ๊ธฐ์ ์ถฉ๋ถํฉ๋๋ค. - Space Efficiency: ์๊ณ ๋ฆฌ์ฆ์ O(1) ์ถ๊ฐ ๊ณต๊ฐ์ ์ฌ์ฉํ๋ฉฐ, ๋น๋ ์นด์ดํฐ๊ฐ ํ์๋ก ํ๋ O(N) ๊ณต๊ฐ๋ณด๋ค ํจ์ฌ ํจ์จ์ ์ ๋๋ค.
- Logic Over Brute Force: ์์ ๋ถํฌ์ ๋ํ ๋น๋๊ธฐ์ง ์๋ฆฌ๋ฅผ ์ดํดํ๋ฉด ๊ฐ๋จํ๊ณ ๋น ๋ฅธ ํด๊ฒฐ์ฑ ์ ์ป์ ์ ์์ต๋๋ค.