LeetCode1365. How Many Numbers Are Smaller Than the Current Number

  • 思路:
  • count[9]=count[9]+1=0+1=1
    count[2]=count[2]+1=0+1=1
    count[3]=count[3]+1=0+1=1
    count[3]=count[3]+1=1+1=2
    count[4]=count[4]+1=0+1=1
    %8  那么比9小的数就+1,1  那么比2小的数就+1,以此类推。但是所有比9小的数,应该是比9小的数+比8小的数。以此类推得到规律:count[i]=count[i]+count[i-1]。从小到大依次求出,最后count[8]中存放的就是所有比8小的数的个数。那么求所有比9小的数的个数时,只需要再在count[9]原来的基础上加上count[8]就可以了。
  • 代码:Python
  • class Solution:
        def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
            count=[0]*102#[0,0,0,0...]
            for num in nums:
                count[num+1]+=1
            for i in range(1,101):
                count[i]+=count[i-1]
            return [count[num]for num in nums]
发布了66 篇原创文章 · 获赞 19 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/RitaAndWakaka/article/details/104970570