Last active
November 1, 2019 04:15
-
-
Save yitonghe00/64ea12ce49ac4e904fc64aca6a923617 to your computer and use it in GitHub Desktop.
287. Find the Duplicate Number (https://leetcode.com/problems/find-the-duplicate-number/): Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Two pointer solution: slow/fast pointer | |
// Time: O(n), 0ms | |
// Space: O(1), 36.8mb | |
class Solution { | |
public int findDuplicate(int[] nums) { | |
// Treat the nums as a singly linked list | |
// The duplicate num is where the cycle begins | |
int slow = 0, fast = 0; | |
while(true) { | |
slow = nums[slow]; | |
fast = nums[nums[fast]]; | |
if(slow == fast) break; | |
} | |
// Find where the cycle begins | |
slow = 0; | |
while(slow != fast) { | |
slow = nums[slow]; | |
fast = nums[fast]; | |
} | |
return slow; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment