|
| 1 | +/** |
| 2 | + * [287] Find the Duplicate Number |
| 3 | + * |
| 4 | + * 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. |
| 5 | + * |
| 6 | + * Example 1: |
| 7 | + * |
| 8 | + * |
| 9 | + * Input: [1,3,4,2,2] |
| 10 | + * Output: 2 |
| 11 | + * |
| 12 | + * |
| 13 | + * Example 2: |
| 14 | + * |
| 15 | + * |
| 16 | + * Input: [3,1,3,4,2] |
| 17 | + * Output: 3 |
| 18 | + * |
| 19 | + * Note: |
| 20 | + * |
| 21 | + * <ol> |
| 22 | + * You must not modify the array (assume the array is read only). |
| 23 | + * You must use only constant, O(1) extra space. |
| 24 | + * Your runtime complexity should be less than O(n^2). |
| 25 | + * There is only one duplicate number in the array, but it could be repeated more than once. |
| 26 | + * </ol> |
| 27 | + * |
| 28 | + */ |
| 29 | +pub struct Solution {} |
| 30 | + |
| 31 | +// submission codes start here |
| 32 | + |
| 33 | +// 假如把值看做 next node 的下标, 那么: |
| 34 | +// 从 0 出发不会回到 0 |
| 35 | +// 一定有环, 因为 1-n 全部落在下标范围 [0, n] 中 |
| 36 | +// 从 0 遍历经过的环中, 一定存在重复数字 x, 且 x 就是入环点的下标: |
| 37 | +// 1.从 0 走到入环点, 入环点的前驱值为 x; 2.入环点在环上的前驱值也是 x |
| 38 | +// 由于我们不可能回到 0, 因此这两个节点下标不同, x 即为要找的重复数字 |
| 39 | +impl Solution { |
| 40 | + pub fn find_duplicate(nums: Vec<i32>) -> i32 { |
| 41 | + let mut slow: usize = nums[0] as usize; |
| 42 | + let mut fast: usize = nums[nums[0] as usize] as usize; |
| 43 | + // util slow meet fast |
| 44 | + while slow != fast { |
| 45 | + slow = nums[slow] as usize; |
| 46 | + fast = nums[nums[fast] as usize] as usize; |
| 47 | + } |
| 48 | + |
| 49 | + fast = 0_usize; |
| 50 | + while slow != fast { |
| 51 | + fast = nums[fast] as usize; |
| 52 | + slow = nums[slow] as usize; |
| 53 | + } |
| 54 | + slow as i32 |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +// submission codes end |
| 59 | + |
| 60 | +#[cfg(test)] |
| 61 | +mod tests { |
| 62 | + use super::*; |
| 63 | + |
| 64 | + #[test] |
| 65 | + fn test_287() { |
| 66 | + assert_eq!(Solution::find_duplicate(vec![1,3,4,2,2]), 2); |
| 67 | + assert_eq!(Solution::find_duplicate(vec![3,1,3,4,2]), 3); |
| 68 | + assert_eq!(Solution::find_duplicate(vec![1,2,3,4,5,5]), 5); |
| 69 | + assert_eq!(Solution::find_duplicate(vec![5,1,2,3,4,5]), 5); |
| 70 | + } |
| 71 | +} |
0 commit comments