博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
287. Find the Duplicate Number
阅读量:6829 次
发布时间:2019-06-26

本文共 1413 字,大约阅读时间需要 4 分钟。

题目:

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.Binary Tree

public int findDuplicate(int[] nums) {    int start = 1, end = nums.length - 1;    while (start + 1 < end) {        int mid = start + (end - start) / 2;        int left = 0, right = 0;        for (int a : nums) {            if (a <= mid) left++;        }               if (left <= mid) start = mid;        else end = mid;    }    int countStart = 0, countEnd = 0;    for (int i = 0; i < nums.length; i++) {        if (nums[i] == start) countStart++;        if (nums[i] == end) countEnd++;    }    return countStart > countEnd ? start : end;}

2.LinkedList Find the starting point of circle

public int findDuplicate(int[] nums) {    int n = nums.length;        int slow = nums[0];    int fast = nums[nums[0]];    while (slow != fast) {        slow = nums[slow];        fast = nums[nums[fast]];    }        fast = 0;    while (slow != fast) {        slow = nums[slow];        fast = nums[fast];    }    return slow;}

转载地址:http://joykl.baihongyu.com/

你可能感兴趣的文章
使用python写糗事百科的爬虫
查看>>
$MFTMirr does not match $MFT (record 0)问题解决
查看>>
oracle 修改列
查看>>
python-03:用最简单快速的方法入门
查看>>
CentOS7网卡绑定
查看>>
LAMP-HTTPD服务器配置
查看>>
linux安装ICMP shell(icmp后门)
查看>>
JSP 上传图片之前先在页面生成预览
查看>>
ICMP协议-路由交换原理4-【HCNA笔记】
查看>>
Performing RMAN Tablespace Point-in-time Recovery(TSPITR)
查看>>
弱引用研究
查看>>
JQuery 判断checkbox是否选中,checkbox全选,获取checkbox选中值
查看>>
高考焦虑现象源于就业焦虑
查看>>
Lync Server 2013企业版部署系列之二:准备DNS
查看>>
启动3个线程轮番打印递增的数字
查看>>
PHP FLUSH 函数 在IE11中 清除缓存的方法
查看>>
lvm相关知识
查看>>
[转] 《全唐诗》《全宋词》
查看>>
C Primer Plus (第五版) 第二章 编程练习
查看>>
安卓开发中Theme.AppCompat.Light的解决方法
查看>>