摘要:复杂度思路每次通过二分法找到一个值之后,搜索整个数组,观察小于等于这个数的个数。考虑,小于这个位置的数的个数应该是小于等于这个位置的。要做的就是像找中的环一样,考虑重复的点在哪里。考虑用快慢指针。代码把一个指针放回到开头的地方
LeetCode[287] Find the Duplicate Number
Binary SearchGiven 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.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
复杂度
O(NlgN), O(1)
思路
每次通过二分法找到一个值之后,搜索整个数组,观察小于等于这个数的个数。
考虑[1,2,3,2],小于这个位置的数的个数应该是小于等于这个位置的。如果cnt > mid,说明在小于这个位置的数的范围内,存在duplicate,right = mid - 1;
代码
public int findDuplicate(int[] nums) { int left = 0, right = nums.length - 1; while(left <= right) { int mid = left + (right - left) / 2; int cnt = 0; for(int i = 0; i < nums.length; i ++) { if(nums[i] <= mid) cnt ++; } if(cnt > mid) right = mid - 1; else left = mid + 1; } return left; }LinkedList判断循环
复杂度
O(N), O(1)
思路
考虑一定会有duplicate出现,说明,数组里面的值组成了一个环,如果考虑像linkedlist那样。
要做的就是像找linkedlist中的环一样,考虑重复的点在哪里。
考虑用快慢指针。
代码
public int findDuplicate(int[] nums) { if(nums.length > 1) { int slow = 0; int fast = 0; while(true) { slow = nums[slow]; fast = nums[nums[fast]]; if(slow == fast) { // case like [1,2,3,1] // 把一个指针放回到开头的地方 slow = 0; while(slow != fast) { slow = nums[slow]; fast = nums[fast]; } return slow; } } } return -1; }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/65263.html
Problem 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 nu...
题目: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,...
摘要:如果的数字都只有一个,那么我们会形成一个闭合的环。如果有重复数字出现的话,如下这里就有一个的环,就是重复数字如果到每个数字都只出现一次,在里的个数应该就是个数大于的话,前面的数字里就会有重复。 // 如果[1,n]的数字都只有一个,那么我们会形成一个闭合的环。 idx 1 2 3 4 val 3 1 4 2 1->3->4->2 这样就是一个闭合的环。 如果有重复数字出现的话,如下:...
Problem 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 nu...
摘要:暴力法复杂度时间空间思路如果不用空间的话,最直接的方法就是选择一个数,然后再遍历整个数组看是否有跟这个数相同的数就行了。二分法复杂度时间空间思路实际上,我们可以根据抽屉原理简化刚才的暴力法。 Find the Duplicate Number Given an array nums containing n + 1 integers where each integer is bet...
阅读 2572·2021-11-02 14:39
阅读 4298·2021-10-11 10:58
阅读 1388·2021-09-06 15:12
阅读 1802·2021-09-01 10:49
阅读 1292·2019-08-29 18:31
阅读 1859·2019-08-29 16:10
阅读 3298·2019-08-28 18:21
阅读 837·2019-08-26 10:42