建图:
举个例子:nums = [2,5, 9 ,6,9,3,8, 9 ,7,1]
,构造成链表就是:2->[9]->1->5->3->6->8->7->[9]
,也就是在[9]
处循环。
按这种方式建好图那么有重复元素必然会有环,而target就是环的入口处
class Solution { public: int findDuplicate(vector<int>& nums) { int slow = 0, fast = 0; do { slow = nums[slow]; fast = nums[nums[fast]]; } while (slow != fast); slow = 0; while (slow != fast) { slow = nums[slow]; fast = nums[fast]; } return slow; } };