Leetcode: Contains Duplicate
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; } };
常見的時間複雜度 O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(n³) < O(2^n) < O(3^n) < O(n!) 我的答案是O(n²),太久了,要想辦法提升效率。 Image Not Showing Possible Reasons The image was uploaded to a note which you don't have access toThe note which the image was originally uploaded to has been deleted Learn More → 圖片來源:http://robot39.blogspot.com/2013/09/computing-power-and-time-complexity.html
改成以下答案就可以被接受了
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; } };
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up