Leetcode summary: array number in the range of array length

这类题一般有个前提:

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array)

442. Find All Duplicates in an Array

class Solution(object):
    def findDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        n=len(nums)
        for i in range(len(nums)):
            nums[(nums[i]-1)%n]+=n
            
        ret=[]
        for i in range(n):
            if nums[i]>2*n:#should be '>', not '>='
                ret.append(i+1)
                
        return ret

optimize version

	res=[]
	        
	for num in nums:
	    
	    index=abs(num)-1
	    
	    if nums[index]<0:
	        res.append(abs(index)+1)
	        
	    nums[index]=-nums[index]
	    
	
	return res

287. Find the Duplicate Number

class Solution(object):
    def findDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums)<=1:
            return -1
        
        fast=nums[nums[0]]
        slow=nums[0]
        
        while slow!=fast:
            fast=nums[nums[fast]]
            slow=nums[slow]
            if slow == fast:
                break
        fast=0
        while True:
            slow=nums[slow]
            fast=nums[fast]
            if slow==fast:
                return slow

565. Array Nesting

class Solution(object):
    def arrayNesting(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        visited=[0 for i in range(len(nums))]
        ret=0
        for i in range(len(nums)):
            cnt=0
            j=i
            while not visited[j]:
                visited[j]=1
                cnt+=1
                j=nums[j]
            
            ret=max(cnt,ret)
        return ret

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值