leetcode287: 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.
陣列中有n+1個數,範圍為1~n,請證明至少存在一個重複的數字。假設只有一個重複的數,請找出這個數。
假設n=4,那麼陣列中應該有5個數,每個數的範圍為1~4且只有一個重複的數字。陣列在放完1 2 3 4 後,如果在放一個數字的話必然會產生重複,目的就是找出這個重複的數字。
要求:
不要更改陣列(限制你不要排序)
不要使用額外的空間(不要建立新的陣列)
時間複雜度小於O(n
思路:
利用二分的思想。初始化一個mid值,如果陣列中小於等於mid的值的個數小於等於mid這個值,那麼可以說明重複數字在mid的右面,反之說明重複數字在mid值的左面。
public class Solution {
public int findDuplicate(int[] nums) {
int n=nums.length-1;
int low=1,high=n;
int mid=0;
//int count2=0;
while(low<high){
int count=0;
mid=(low+high)/2;
for(int i=0;i<nums.length;i++){
if(nums[i]<=mid)count++;
}
if(count<=mid) low=mid+1;
else high=mid;
}
return low;
}
}
相關文章
- [LeetCode] Find the Duplicate NumberLeetCode
- LeetCode-Find the Duplicate NumberLeetCode
- LeetCode 題解(252) : Find the Duplicate NumberLeetCode
- LeetCode 1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance??LeetCode
- Martyr2專案實現——Number部分的問題求解 (1) Find Pi to Nth DigitGit
- duplicate databaseDatabase
- RMAN duplicate databaseDatabase
- JavaScript Number()JavaScript
- Oracle System Change Number (SCN) Number 完全筆記Oracle筆記
- yum error - package is a duplicate withErrorPackage
- jQuery find()jQuery
- find 命令
- find命令
- 【NUMBER】Oracle的NUMBER資料型別特點Oracle資料型別
- JavaScript Number 物件JavaScript物件
- Number.NaNNaN
- Number of BoomerangsOOM
- DUPLICATE DATABASE 注意事項Database
- 通過rman duplicate database!Database
- RMAN duplicate On Windows7Windows
- find -newer命令
- JavaScript find()方法JavaScript
- Linux findLinux
- How to find dependency
- find process by port
- react input[type='number']React
- JavaScript Number toLocaleString()JavaScript
- JavaScript Number toString()JavaScript
- Number.POSITIVE_INFINITY
- Number.ATIVE_INFINITY
- Number.isNaN()方法NaN
- Number.isFinite()方法
- Js中的NumberJS
- Where is the SCN number written?
- D. The Number of Imposters
- rman duplicate操作手冊
- Duplicate的一點總結
- Oracle DG搭建1(duplicate方式)Oracle