Try   HackMD

Contains Duplicate Emma C++ Note

Programming Language: C++

Back to Leetcode Blind 75 Practice Note

Leetcode: Contains Duplicate

  • 一開始寫的code,顯示time limit exceeded,BigO是O(n^2)
    超過Leetcode可接受的效能了,並不代表答案錯誤,是效能太差
    參考這篇文
    Image Not Showing Possible Reasons
    • The image was uploaded to a note which you don't have access to
    • The note which the image was originally uploaded to has been deleted
    Learn More →
class Solution { public: bool containsDuplicate(vector<int>& nums) { int allNumCount = nums.size(); int sameNumCount = 0; bool boolRepeatNum = false; for ( int i = 0; i < allNumCount; i++ ) { for ( int j = i+1; j < allNumCount; ) { if (nums[i] == nums[j]) { boolRepeatNum = true; return boolRepeatNum; } } } return boolRepeatNum; } };
class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {

        sort(nums.begin(), nums.end()); // 先由小到大排序
        int allNumCount = nums.size();

        for ( int i = 1; i < allNumCount; i++ )
        {
            if (nums[i] == nums[i-1])
                return true;
        }
        return false;
    }
};