Leetcode之 Find the Duplicate Numbe

题目描述:
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.

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.

难就难在:
1. 不准改变这个array,所以也就没法先排序再选出duplicate的数了
2. 只允许用O(1)的extra空间,所以没法像之前的find missing number一样,重新新建一个数组保存每个值的状态

看了很多解法,感觉有一个解法很妙:
一个有重复数字的array,科表示为:
0:1
1:2
2 : 3
3:4
4:6
5:3
6:3
7:5
这样的话一定能形成一个圈: 0->1->2->3->4->6->3->3->4->6->3…..
也就把这个问题转化为了LindedList问题中的求cycle的起点(使用快慢指针法)的问题,这个问题在之前已经写过了。

代码如下:

public class FindDuplicateNum {
    public int findDuplicate(int[] nums) {
           int slow=0,fast=0;
           while(true){
               slow=nums[slow];
               fast=nums[nums[fast]];
               if(slow==fast)
                    break;
           }
           slow=0;
           while(true){
               slow=nums[slow];
               fast=nums[fast];
               if(slow==fast)
                    return slow;
           }

        }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值