leetcode 287. Find the Duplicate Number 数组重复元素查询 + 环的存在判定 + 快慢指针 + 很妙的想法

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.

因为数组的内容和下标范围是一致的,所以可以考虑作为一个链表来做,我在网上看到了一个使用类似快慢指针的做法去做,想法很棒。

不过最最直接的方法还是使用HashMap来完成计数。

代码如下:



/*
 * https://discuss.leetcode.com/topic/25685/java-o-n-time-and-o-1-space-solution-similar-to-find-loop-in-linkedlist
 * 
 * 这个题很巧,可以利用寻找链表是否存在环的方法判断
 * 技巧性很强,需要好好想一下
 * */
class Solution 
{
    public int findDuplicate(int[] nums) 
    {
        if(nums==null || nums.length<=1)
            return 0;
        int slow=nums[0];
        int fast=nums[nums[0]];
        while(fast!=slow)
        {
            slow=nums[slow];
            fast=nums[nums[fast]];
        }
        slow=0;
        while(fast!=slow)
        {
            slow=nums[slow];
            fast=nums[fast];
        }
        return slow;
    }
}

下面是C++的做法,就是使用双指针做一个遍历,注意这个题很巧妙,可以使用双指针来做。

代码如下:

#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>

using namespace std;

class Solution 
{
public:
    int findDuplicate(vector<int>& a) 
    {
        int slow = a[0];
        int fast = a[slow];
        while (fast != slow)
        {
            slow = a[slow];
            fast = a[a[fast]];
        }
        slow = 0;
        while (fast != slow)
        {
            slow = a[slow];
            fast = a[fast];
        }
        return fast;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值