|
| 1 | +/* |
| 2 | +Clarifications |
| 3 | +1) Is this sorted Array? |
| 4 | +2) What is the maximum / minimum value in nums? |
| 5 | +
|
| 6 | +Solutions |
| 7 | +1) Brute force - two nested for loop |
| 8 | +T(C): O(n^2) |
| 9 | +S(C): O(1) |
| 10 | +2) Sort - Mergesort or library sort(Merge+quick) |
| 11 | +T(C) : O(NlogN) |
| 12 | +S(C) : O(N) |
| 13 | +3) Hash |
| 14 | +T(C) : O(1) |
| 15 | +S(C) : O(N) |
| 16 | +*/ |
| 17 | + |
| 18 | +class Solution { |
| 19 | +public: |
| 20 | + // Solution 2-1) Library Sort |
| 21 | + // bool containsDuplicate(vector<int>& nums) { |
| 22 | + // sort(nums.begin(), nums.end()); |
| 23 | + // for (size_t i = 0; i < nums.size() - 1; i++) |
| 24 | + // { |
| 25 | + // if (nums[i] == nums[i + 1]) |
| 26 | + // return true; |
| 27 | + // } |
| 28 | + // return false; |
| 29 | + // } |
| 30 | + |
| 31 | + // Solution 2-2) Implement Sort |
| 32 | + void mergeSort(vector<int>& nums, int start, int end, vector<int>& temp) |
| 33 | + { |
| 34 | + if (start >= end) |
| 35 | + return; |
| 36 | + int mid = (start + end) / 2; |
| 37 | + mergeSort(nums, start, mid, temp); |
| 38 | + mergeSort(nums, mid + 1, end, temp); |
| 39 | + int i = start, j = mid + 1, k = start; |
| 40 | + while (i <= mid && j <= end) |
| 41 | + { |
| 42 | + if (nums[i] < nums[j]) |
| 43 | + temp[k++] = nums[i++]; |
| 44 | + else |
| 45 | + temp[k++] = nums[j++]; |
| 46 | + } |
| 47 | + while (i <= mid) |
| 48 | + temp[k++] = nums[i++]; |
| 49 | + while (j <= end) |
| 50 | + temp[k++] = nums[j++]; |
| 51 | + for (int p = start; p <= end; p++) |
| 52 | + nums[p] = temp[p]; |
| 53 | + } |
| 54 | + // Solution 1-2) Library Sort |
| 55 | + // bool containsDuplicate(vector<int>& nums) { |
| 56 | + // vector<int> temp(nums.size(), 0); |
| 57 | + // mergeSort(nums, 0, nums.size() - 1, temp); |
| 58 | + // for (size_t i = 0; i < nums.size() - 1; i++) |
| 59 | + // { |
| 60 | + // if (nums[i] == nums[i + 1]) |
| 61 | + // return true; |
| 62 | + // } |
| 63 | + // return false; |
| 64 | + // } |
| 65 | + |
| 66 | + // solution 2 - hash |
| 67 | + bool containsDuplicate(vector<int>& nums) { |
| 68 | + unordered_map<int, int> hash; |
| 69 | + for (size_t i = 0; i < nums.size(); i++) |
| 70 | + { |
| 71 | + if (hash.find(nums[i]) != hash.end()) |
| 72 | + return true; |
| 73 | + hash[nums[i]] = i; |
| 74 | + } |
| 75 | + return false; |
| 76 | + } |
| 77 | +}; |
0 commit comments