넘치게 채우기

[LeetCode] 217. Contains Duplicate 본문

PS/LeetCode

[LeetCode] 217. Contains Duplicate

riveroverflow 2023. 10. 4. 10:35
728x90
반응형

https://leetcode.com/problems/contains-duplicate/description/

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제 유형 : 해시, 배열

문제 난이도 : Easy

 

문제

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

 

배열에서 같은 요소가 하나라도 두 번 이상 등장하면 true를 반환하고, 아니면 false를 반환하시오.

 

풀이

해시 테이블을 만들어서 풀어 보았다.

key를 요소, value를 횟수로 해서, value가 2가 넘는걸 감지한다면 true를, 배열 내내 한 번도 그렇지 못했다면 false를 반환한다.

 

코드

C++

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        ios_base::sync_with_stdio(false);
        cin.tie(nullptr);
        cout.tie(nullptr);

        unordered_map<int, int> s;
        for(const auto& num : nums) {
            s[num]++;
            if(s[num] >= 2) return true;
        }

        return false;
    }
};
 
728x90
반응형