zoukankan      html  css  js  c++  java
  • 287. Find the Duplicate Number

    这个题与那个LIST套环的其实是一回事。

    把nums[]想象成C里面的array of pointers,元素就是指向位置,INDEX就是他的位置。

    之所以可以这样想象,是因为题里说了1-n+1个元素出现在size为n的ARRAY里。

    一开始想的是1个pointer遍历就行,从nums[0]开始,记住他指的位置,然后把nums[0]标记成0或者-1,证明我们来过,然后去它指的位置,下一个也这样,最终会发现当前的NODE指引我们去一个曾经去过的地方,那么当前元素就是要找的那个。

    public int findDuplicate(int[] nums) 
        {
            //if(nums.length == 2) return nums[0];
            
            int next = nums[0];
            int cur = 0;
            nums[cur] = -1;
            while(true)
            {
                if(nums[next] == -1) return next;
                cur = next;
                next = nums[cur];
                nums[cur] = -1;
                
            }
            
        }
    

    再然后发现卧槽
    You must not modify the array (assume the array is read only).

    那只好快慢指针。。第一次相遇BREAK,然后新的慢指针从头出发,新旧慢指针相遇的位置就是要求的。

    public class Solution 
    {
        public int findDuplicate(int[] nums) 
        {
            if(nums.length <= 2) return nums[0];
            int i1 = 0;
            int i2 = 0;
            
            while(true)
            {
                i1 = nums[i1];
                i1 = nums[i1];
                i2 = nums[i2];
                if(i1 == i2) break;
            }
            
            i1 = 0;
            while(i1 != i2)
            {
                i1 = nums[i1];
                i2 = nums[i2];
            }
            
            return i1;
            
    
        }
    }
    
  • 相关阅读:
    对于“口袋精灵”单元测试
    12-17:项目进度
    12-15:项目进度
    12-14:项目进度
    12-13:项目进度
    12-12:项目进度
    12-11:项目进度
    12-10:项目进度
    12-9:项目进度
    12-6:项目进度
  • 原文地址:https://www.cnblogs.com/reboot329/p/5888286.html
Copyright © 2011-2022 走看看