|
| 1 | +"Leetcode- https://leetcode.com/problems/find-the-duplicate-number/ " |
| 2 | +''' |
| 3 | +Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. |
| 4 | + |
| 5 | +There is only one repeated number in nums, return this repeated number. |
| 6 | + |
| 7 | +You must solve the problem without modifying the array nums and uses only constant extra space. |
| 8 | + |
| 9 | +Example 1: |
| 10 | + |
| 11 | +Input: nums = [1,3,4,2,2] |
| 12 | +Output: 2 |
| 13 | +''' |
| 14 | + |
| 15 | +# Solution-1 |
| 16 | +def findDuplicate(self, nums): |
| 17 | + nums.sort() |
| 18 | + |
| 19 | + for i in range(len(nums)): |
| 20 | + if nums[i] == nums[i-1]: |
| 21 | + return nums[i] |
| 22 | + |
| 23 | +# T:O(nlogn) |
| 24 | +# S:O(n) |
| 25 | + |
| 26 | +# Solution-2- using set |
| 27 | +def findDuplicate(self, nums): |
| 28 | + seen = set() |
| 29 | + for num in nums: |
| 30 | + if num in seen: |
| 31 | + return num |
| 32 | + seen.add(num) |
| 33 | + |
| 34 | +# T:O(n) |
| 35 | +# S:O(n) |
| 36 | + |
| 37 | +# Solution-3- Binary Search |
| 38 | +def findDuplicate(self, nums): |
| 39 | + # 'low' and 'high' represent the range of values of the target |
| 40 | + low = 1 |
| 41 | + high = len(nums) - 1 |
| 42 | + |
| 43 | + while low <= high: |
| 44 | + cur = (low + high) // 2 |
| 45 | + count = 0 |
| 46 | + |
| 47 | + # Count how many numbers are less than or equal to 'cur' |
| 48 | + count = sum(num <= cur for num in nums) |
| 49 | + if count > cur: |
| 50 | + duplicate = cur |
| 51 | + high = cur - 1 |
| 52 | + else: |
| 53 | + low = cur + 1 |
| 54 | + |
| 55 | + return duplicate |
| 56 | + |
| 57 | +# T:O(nlogn) |
| 58 | +# S:O(1) |
| 59 | + |
| 60 | +# Solution-4- Two Pointers Floyd's Tortoise and Hare (Cycle Detection) |
| 61 | +def findDuplicate(self, nums): |
| 62 | + # Find the intersection point of the two runners. |
| 63 | + to = hr = nums[0] |
| 64 | + while True: |
| 65 | + to = nums[to] |
| 66 | + hr = nums[nums[hr]] |
| 67 | + if to == hr: |
| 68 | + break |
| 69 | + |
| 70 | + # Find the "entrance" to the cycle. |
| 71 | + to = nums[0] |
| 72 | + while to != hr: |
| 73 | + to = nums[to] |
| 74 | + hr = nums[hr] |
| 75 | + |
| 76 | + return hr |
| 77 | + |
| 78 | +# T:O(n) |
| 79 | +# S:O(1) |
0 commit comments