LeetCode - 217. Contains Duplicate - 思路詳解 - C++

題目

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.

翻譯

假設有一個數組,判斷該數組是否存在重複的數。

思路

思路1,暴力法,雙層循環,時間複雜度O(n^2)
思路2,快排,之後找重複。時間複雜度O(nlgn)

代碼

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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章