前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 0287 - Find the Duplicate Number

LeetCode 0287 - Find the Duplicate Number

作者头像
Reck Zhang
发布2021-08-11 11:51:39
3000
发布2021-08-11 11:51:39
举报
文章被收录于专栏:Reck Zhang

Find the Duplicate Number

Desicription

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.

Example 1:

代码语言:javascript
复制
Input: [1,3,4,2,2]
Output: 2

Example 2:

代码语言:javascript
复制
Input: [3,1,3,4,2]
Output: 3

Note:

  1. You must not modify the array (assume the array is read only).
  2. You must use only constant, O(1) extra space.
  3. Your runtime complexity should be less than O(n^2).
  4. There is only one duplicate number in the array, but it could be repeated more than once.

Solution

代码语言:javascript
复制
class Solution {
public:
    int findDuplicate(vector<int>& nums) {
        if(nums.size() <= 1) {
            return 0;
        }
        int slow = nums[0];
        int first = nums[nums[0]];
        while(slow != first) {
            slow = nums[slow];
            first = nums[nums[first]];
        }
        first = 0;
        while(first != slow) {
            slow = nums[slow];
            first = nums[first];
        }
        return slow;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-12-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Find the Duplicate Number
    • Desicription
      • Solution
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档