zoukankan      html  css  js  c++  java
  • 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
     
     
  • 相关阅读:
    Java Web入门二
    Java web入门之Http请求和响应
    Java中的heap和stack
    JSP和Servlet的区别和联系
    MVC设计思想
    Java中int和Integer的区别
    Java使用文件通道复制文件
    Maven项目的pom.xml配置文件格式初识
    面向对象编程思想
    1.struts 防止表单重复提交 2. 拦截器
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13888214.html
Copyright © 2011-2022 走看看