Note:
- You must not modify the array (assume the array is read only).
- You must use only constant, O(1) extra space.
- Your runtime complexity should be less than
O(n2)
. - There is only one duplicate number in the array, but it could be repeated more than once.
這題要利用link list cycle II 的解法
因為這個陣列只包含1~n
所以可以看成是圖型 第0個點 下一點要去哪
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | int findDuplicate(int* nums, int numsSize) { //like link list cycle int slow=0,fast=0; while(true){ int slowindex=slow,fastindex=fast; slow=nums[slowindex]; fast=nums[nums[fastindex]]; //printf("A%d %d,%d %dA",slow,slowindex,fast,fastindex); if(slow==fast)break; } int find=0; while(true){ find = nums[find]; slow = nums[slow]; if(find==slow)return find; } } |
沒有留言:
張貼留言