LeetCode 217. Contains Duplicate

margarin·2021년 2월 17일
0

알고리즘

목록 보기
7/13

문제

217. Contains Duplicate
Given an array of integers, find if the array contains any duplicates.

Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

Example 1:

Input: [1,2,3,1]
Output: true

풀이방법

같은 수가 두번 나오면 true를 리턴하면 된다.
LeetCode는 시간초과나는 문제가 많기 때문에 최대한 for문을 한번만 돌려야한다고 생각했다. 알고리즘 초보인 내가 봐도 쉬운편이었다..🤔
vector를 sort하고,
i번째와 i+1번째가 같으면 true를 리턴, 마지막까지 같지 않다면 false를 리턴한다.
다만 테스트케이스에 빈 벡터([])가 있어서 벡터 사이즈를 체크해서 먼저 리턴했다.

코드

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        if (nums.size() == 0) return false;
        sort(nums.begin(), nums.end());
        for (int i = 0; i < nums.size() - 1; i++){
            if (nums[i] == nums[i+1]) {
                return true;
            }
        }
        return false;
    }
};
profile
화이팅 🥹

0개의 댓글