|
| 1 | +/* |
| 2 | + * Copyright (C) 2022, Saul Lawliet <october dot sunbathe at gmail dot com> |
| 3 | + * All rights reserved. |
| 4 | + * |
| 5 | + * https://leetcode.com/problems/find-the-duplicate-number/ |
| 6 | + * Q: 在一个长度为n+1的数组中, 里面是元素是 [1, n], 只有一个数字是重复的, 找到它 |
| 7 | + * (不允许修改数字的元素; 使用常量空间; 1 <= n <= 100000) |
| 8 | + * |
| 9 | + * 第一次读题, 以为是一个数字出现2次, 其他数字都出现了1次, 这不用数学运算就能计算出来么, 然后就被 [2,2,2,2,2] 的测试用例教育了. |
| 10 | + * 不允许修改数字元素+使用常量空间, 就排除了排序法、利用数组空间标记法、位存储法... |
| 11 | + * |
| 12 | + * 看了解题思路, 只有这个解符合规定: https://en.wikipedia.org/wiki/Cycle_detection#Floyd's_tortoise_and_hare |
| 13 | + */ |
| 14 | + |
| 15 | +#include "c/data-structures/array.h" |
| 16 | +#include "c/test.h" |
| 17 | + |
| 18 | +int findDuplicate(int *nums, int numsSize) { |
| 19 | + // 乌龟走一步, 兔子走两步, 直到相遇 |
| 20 | + int tortoise = nums[0], hare = nums[0]; |
| 21 | + do { |
| 22 | + tortoise = nums[tortoise]; |
| 23 | + hare = nums[nums[hare]]; |
| 24 | + } while (tortoise != hare); |
| 25 | + |
| 26 | + // 相遇后, 乌龟去起点, 双方每次走一步, 相遇的地方就是环状起点 |
| 27 | + tortoise = nums[0]; |
| 28 | + |
| 29 | + while (tortoise != hare) { |
| 30 | + tortoise = nums[tortoise]; |
| 31 | + hare = nums[hare]; |
| 32 | + } |
| 33 | + |
| 34 | + return hare; |
| 35 | +} |
| 36 | + |
| 37 | +void test(int expect, const char *nums) { |
| 38 | + arrayEntry *e = arrayParse1D(nums, ARRAY_INT); |
| 39 | + |
| 40 | + EXPECT_EQ_INT(expect, findDuplicate(arrayValue(e), arraySize(e))); |
| 41 | + |
| 42 | + arrayFree(e); |
| 43 | +} |
| 44 | + |
| 45 | +int main(void) { |
| 46 | + test(2, "[1,3,4,2,2]"); |
| 47 | + test(3, "[3,1,3,4,2]"); |
| 48 | + |
| 49 | + // 以下是提交错误时的测试用例 |
| 50 | + test(2, "[2,2,2,2,2]"); |
| 51 | + test(9, "[2,5,9,6,9,3,8,9,7,1]"); |
| 52 | + |
| 53 | + return testOutput(); |
| 54 | +} |
0 commit comments