(Leetcode) [Array]: Contains duplicate

Topic: Array
Difficulty: Easy

Array element ์ค‘์— ํ•˜๋‚˜๋ผ๋„ ์ค‘๋ณต๋˜๋Š” ๊ฒŒ ์žˆ์œผ๋ฉด return true; else return false.

Solution

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        vector<int> temp;

        for (int i=0; i<nums.size(); i++) {
            if (find(temp.begin(), temp.end(), nums[i]) != temp.end())
                return true;
            temp.push_back(nums[i]);
        }
        return false;
    }
};

์ฒซ ๋ฒˆ์งธ๋กœ ํ’€์—ˆ๋˜ ๋ฌธ์ œ (two sum)์„ ์ธ์šฉํ•ด์„œ ํ’€์—ˆ๋‹ค.
for loop์„ ์ด์šฉํ•ด์„œ temp๋ผ๋Š” ์ž„์˜์˜ ๋ฒกํ„ฐ์— ์ˆซ์ž๋ฅผ ํ•˜๋‚˜์”ฉ ๋„ฃ๋Š”๋ฐ, ๋„ฃ๊ธฐ ์ „์— temp ์•ˆ์— ๋„ฃ์œผ๋ ค๋Š” ์ˆซ์ž์™€ ๊ฐ™์€ ์ˆซ์ž๊ฐ€ ์žˆ์œผ๋ฉด return true.
์—†์œผ๋ฉด temp์— ์ €์žฅํ•˜๊ณ  loop ๊ณ„์† ๋ฐ˜๋ณต.

๊ฒฐ๊ณผ:
runtime์€ ์ƒ์œ„ 95ํผ์ด๋‹ค (2941 ms); ๋” ํšจ์œจ์ ์ธ ๋ฐฉ๋ฒ•์ด ์žˆ๋‚˜๋ณด๋‹ค.
memory๋Š” ์ƒ์œ„ 30ํผ (47.4 MB). ๋‚˜๋ฆ„ ์„ ๋ฐฉํ•œ๋“ฏ?


์—ฌ๋Ÿฌ๊ฐ€์ง€์˜ ๋‹ต์•ˆ์ด ์žˆ์—ˆ๋‹ค. ๊ทธ ์ค‘ ์„ธ ๊ฐœ๋ฅผ ์†Œ๊ฐœํ•œ๋‹ค.

1. Use of set (unordered_set)

๊ณ ์œ ํ•œ ์š”์†Œ๋งŒ ์œ ์ง€ํ•˜๋Š” ๋ฐฐ์—ด์—์„œ ์ง‘ํ•ฉ์„ ๊ตฌ์„ฑํ•œ๋‹ค. ๊ทธ๋Ÿฐ ๋‹ค์Œ ์ง‘ํ•ฉ์˜ ํฌ๊ธฐ๋ฅผ ๋ฐฐ์—ด์˜ ๊ธธ์ด์™€ ๋น„๊ตํ•œ๋‹ค.
๋‘˜์˜ ํฌ๊ธฐ๊ฐ€ ๊ฐ™์œผ๋ฉด ์ค‘๋ณต ์—†์Œ, ๋‹ค๋ฅด๋ฉด ์ค‘๋ณต ์žˆ์Œ.

bool containsDuplicate(vector<int>& nums) {
    unordered_set<int> temp(nums.begin(), nums.end());

    if (temp.size() == nums.size())
        return false;
    else
        return true;
}

๊ฒฐ๊ณผ: runtime์€ 10๋ฐฐ ์ด์ƒ ๋นจ๋ผ์ง (211 ms = ์ƒ์œ„ 89ํผ). ๋Œ€์‹  ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ์€ ์ฆ๊ฐ€ (55.3MB = ์ƒ์œ„ 94ํผ)

2. Use of sort

๋ฐฐ์—ด์„ ์ •๋ ฌํ•˜๊ณ  ์—ฐ์† ์š”์†Œ์˜ ๊ฐ ์Œ์„ ๋น„๊ตํ•˜์—ฌ ์ค‘๋ณต์„ ํ™•์ธํ•œ๋‹ค.
Time complexity: O(nlog(n)).

bool containsDuplicate(vector<int>& nums) {
    sort(nums.begin(), nums.end());
    for (int i=0; i<nums.size()-1; i++) {
        if (nums[i]==nums[i+1])
            return true;
    }
    return false;
}

๊ฒฐ๊ณผ: runtime 149 ms (์ƒ์œ„ 53ํผ), ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ 46.6 MB (์ƒ์œ„ 20ํผ).

3. Use of adjacent_find

std::adjacent_find: ์ •๋ ฌ๋œ ๋ฐฐ์—ด์—์„œ ๋™์ผํ•œ ์ธ์ ‘ ์š”์†Œ์˜ ์ฒซ ๋ฒˆ์งธ ๋ฐœ์ƒ์„ ์ฐพ๋Š”๋‹ค.
์ค‘๋ณต์ด ์žˆ์œผ๋ฉด ์ฒซ ๋ฒˆ์งธ ์ค‘๋ณต ์š”์†Œ์˜ ๋ฐ˜๋ณต์ž๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค. ์—†์œผ๋ฉด ๋ฒ”์œ„ ๋์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

bool containsDuplicate(vector<int>& nums) {
    sort(nums.begin(), nums.end());
    
    if (adjacent_find(nums.begin(), nums.end()) != nums.end())
        return true;
    else 
        return false;
}

๊ฒฐ๊ณผ: runtime 114 ms (์ƒ์œ„ 20ํผ), ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ 46.7 MB (์ƒ์œ„ 20ํผ).

Categories:

Updated:

Leave a comment