博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
数组和矩阵(1)——Find the Duplicate Number
阅读量:4707 次
发布时间:2019-06-10

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

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:

  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(n2).                  //不能暴力求解
  4. There is only one duplicate number in the array, but it could be repeated more than once.

https://segmentfault.com/a/1190000003817671#articleHeader4

考虑:

  1. 暴力求解,选择一个数,看有没有重复的;
  2. 哈希表
  3. 排序后遍历
  4. 二分法
  5. 设置快慢指针,映射找环法
1 public class Solution { 2     public int findDuplicate(int[] nums) { //映射找环 3         int n = nums.length - 1; 4         int pre = 0; 5         int last = 0; 6         do { 7             pre = nums[pre]; 8             last = nums[nums[last]]; 9         } while(nums[pre] != nums[last]);10         last = 0;11         while(nums[pre] != nums[last]) {12             pre = nums[pre];13             last = nums[last];14         }15         return nums[last];16     }17 }

 

转载于:https://www.cnblogs.com/-1307/p/6905979.html

你可能感兴趣的文章
HDU-2073 无限的路
查看>>
WPF绘制折线
查看>>
NSarray 赋值 拷贝 等问题记录
查看>>
第八篇 CSS定位
查看>>
Android基础之五:四大组件(Broadcast Receiver)
查看>>
P3233 [HNOI2014]世界树
查看>>
P4878 [USACO05DEC]layout布局(差分约束)
查看>>
软件工程——github地址
查看>>
读后感
查看>>
[java杂记]java8的lamada 表达式
查看>>
IT职场人的“存在主义”
查看>>
VXLAN实验
查看>>
python时间模块和random模块
查看>>
John Deere Service Advisor EDL V2 Diagnostic Kit
查看>>
一、设计模式简介
查看>>
Android 多线程 打地鼠游戏
查看>>
ORM关联表模型
查看>>
sgu 138
查看>>
uva 11627
查看>>
让Java swing 中的JTextArea换行
查看>>