LeetCode Top 100 Liked Questions 287. Find the Duplicate Number (Java版; Medium)
题目描述
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:
Input: [1,3,4,2,2]
Output: 2
Example 2:
Input: [3,1,3,4,2]
Output: 3
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,n]这个范围进行二分, 并不是对nums二分
classSolution{publicintfindDuplicate(int[] nums){//核心:对[1,n]这个范围进行二分, 并不是对nums二分int left =1, right = nums.length-1, mid;while(left < right){
mid = left +(right - left)/2;int count =0;for(int a : nums){if(a<=mid){
count++;}}//如果小于等于mid的数没有重复的话, 那么count==mid;此时说明重复的数字出现在[mid+1,n]中//如果小于等于mid的数有重复的话, 那么count>midif(count>mid){
right = mid;}else{
left = mid+1;}}return left;}}
classSolution{publicintfindDuplicate(int[] nums){//数组长度必须大于等于2/*
最核心:
index看成节点引用
nums[index]看成节点的val
nums[index]还要看成next指针
*/int left=0, right=nums[0];while(nums[left]!= nums[right]){//慢指针一次走一步
left = nums[left];//快指针一次走两步; 可以写成一句right = nums[nums[right]
right = nums[right];
right = nums[right];}//
right = nums[right];
left =0;while(nums[left]!= nums[right]){
left = nums[left];
right = nums[right];}return nums[left];}}
LeetCode Top 100 Liked Questions 287. Find the Duplicate Number (Java版; Medium)
welcome to my blogLeetCode Top 100 Liked Questions 287. Find the Duplicate Number (Java版; Medium)题目描述Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive),...