287. Find the Duplicate Number 找出数组中的重复数字

Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.

There is only one duplicate number in nums, return this duplicate number.

Follow-ups:

  1. How can we prove that at least one duplicate number must exist in nums
  2. Can you solve the problem without modifying the array nums?
  3. Can you solve the problem using only constant, O(1) extra space?
  4. Can you solve the problem with runtime complexity less than O(n2)?

 

Example 1:

Input: nums = [1,3,4,2,2]
Output: 2

Example 2:

Input: nums = [3,1,3,4,2]
Output: 3

Example 3:

Input: nums = [1,1]
Output: 1

Example 4:

Input: nums = [1,1,2]
Output: 1

怎么优化的思路:快慢指针,好像是哦


还得重设fast = 0,让它追赶slow

 

class Solution {
    public int findDuplicate(int[] nums) {
        //cc
        if (nums == null || nums.length == 0)
            return 0;
        
        //初始化,不是0,而是nums[0]
        int slow = nums[0];
        int fast = nums[nums[0]];
        
        //先找到slow
        while (fast != slow) {
            slow = nums[slow];
            fast = nums[nums[fast]];
        }
        
        //然后让fast去追赶这个slow
        fast = 0;
        while (fast != slow) {
            slow = nums[slow];
            fast = nums[fast];
        }
        
        //返回
        return fast;
    }
}
View Code

 

 
 
posted @ 2020-10-27 22:36  苗妙苗  阅读(75)  评论(0编辑  收藏  举报