반응형
    
    
    
  https://leetcode.com/problems/n-repeated-element-in-size-2n-array/description/
N-Repeated Element in Size 2N Array - LeetCode
Can you solve this real interview question? N-Repeated Element in Size 2N Array - You are given an integer array nums with the following properties: * nums.length == 2 * n. * nums contains n + 1 unique elements. * Exactly one element of nums is repeated n
leetcode.com
자료구조 map을 사용해보는 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
정답 변수 ans를 선언합니다.
📔 풀이과정
📑 map 사용
key에는 nums[i]값 value에는 해당 값의 빈도수를 저장합니다.value가 1을 초과한다면 key를 반환하면 됩니다.
📑 vector 사용
nums[i]의 크기가 최대 1만이므로 counting sort처럼 구현이 가능합니다. 1만까지의 배열 공간을 선언 후 값에는 빈도 수를 저장하면서. 빈도수가 1을 초과하는 index를 반환합니다.
📔 정답 출력 | 반환
ans를 반환합니다.
📕 Code
📔 C++
📑 map 사용
class Solution {
public:
    int repeatedNTimes(vector<int>& nums) {
        
        map <int,int> freqMap;
        int ans = 1;
        for(auto n : nums) {
          freqMap[n]++;
            if(freqMap[n] > 1) {ans = n; break;}
        }
   
        return ans;
    }
};📑 vector 사용
class Solution {
    vector <int> cnt;
public:
    Solution() {
        cnt.resize(10001, 0);
    }
    int repeatedNTimes(vector<int>& nums) {
        int ans;
        for(auto n : nums) {
            if(cnt[n]) {
                ans = n;
                break;
            }
            cnt[n]++;
        }
        return ans;
    }
};📔 Rust
📑 map 사용
use std::collections::HashMap;
impl Solution {
    pub fn repeated_n_times(nums: Vec<i32>) -> i32 {
        let mut m = HashMap::new();
        let mut ans = 1;
        for n in nums {
            let mVal = m.get(&n);
            if let Some(_) = mVal {
                ans = n;
                break;
            } else {
                m.insert(n, 1);
            }
        }
        return ans;
    }
}*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.