本题其实也谈不上难,但是确实有一定的思维难度,需要把这道题转化为LinkedList Cycle,才容易做出。
    首先谈一下为什么可以转化为LinkedList Cycle:

    • 举例: [1, 3, 4, 2, 2]
    • 转化为LinkedList:
      • index是value
      • value是指next
      • 有点绕,画个图表示一下: 287. Find the Duplicate Number - 图1
      • 但凡有duplicate number存在,则必然有两个位置指向同一个node的情况,比如1 -> 3, 4 -> 3,这就是环的存在

    这个想明白之后,余下的部分就比较简单了,就是单纯的

    • 确定Cycle长度
    • 找环的起点

    • 时间复杂度:287. Find the Duplicate Number - 图2

    • 空间复杂度:287. Find the Duplicate Number - 图3

    代码如下:

    1. class Solution {
    2. public int findDuplicate(int[] nums) {
    3. // step 1: find length of cycle, if no cycle, skip
    4. int len = 0;
    5. int slow = 0;
    6. int fast = 0;
    7. while (true) {
    8. fast = nums[fast];
    9. fast = nums[fast];
    10. slow = nums[slow];
    11. ++len;
    12. if (fast == slow) {
    13. break;
    14. }
    15. }
    16. // step 2
    17. slow = 0;
    18. fast = 0;
    19. while (len > 0) {
    20. fast = nums[fast];
    21. --len;
    22. }
    23. while (slow != fast) {
    24. slow = nums[slow];
    25. fast = nums[fast];
    26. }
    27. return slow;
    28. }
    29. }