zoukankan      html  css  js  c++  java
  • 1365. 有多少小于当前数字的数字





    代码一:用字典。

    class Solution(object):
        def smallerNumbersThanCurrent(self, nums):
            """
            :type nums: List[int]
            :rtype: List[int]
            """
            mydict = {}
            temp = []
            for i, v in enumerate(nums):
                temp.append(i)
                if v in mydict.keys():
                    mydict[v] += temp
                else:
                    mydict[v] = temp
                temp = []
            newList = sorted(mydict.items(), key=lambda item: item[0], reverse=True)
            # print(newList)
            # 记录原list的元素个数
            count = len(nums)
            ans = [0 for _ in range(count)]
            for i in range(len(newList)):
                # 同值元素的下标
                indexList = newList[i][1]
                # 更新计数器
                count -= len(indexList)
                # 同值元素的结果相同
                for index in indexList:
                    ans[index] = count
            return ans
    

    代码二:暴力。

    class Solution(object):
        def smallerNumbersThanCurrent(self, nums):
            """
            :type nums: List[int]
            :rtype: List[int]
            """
            ans = []
            for i in nums:
                ans.append(self.smallCount(nums, i))
            return ans
    
        # 统计数组中比n小的数的个数
        def smallCount(self, nums, n):
            if not nums:
                return 0
            ans = 0
            for item in nums:
                if item < n:
                    ans += 1
            return ans
    
  • 相关阅读:
    WebView用法与JS交互(2) 响应webview中的图片点击事件
    出栈序列(栈和队列)
    Log Files
    Mr. Frog’s Game
    Comparison of Android versions
    Linearization of the kernel functions in SVM
    Game of Nuts
    Easy Summation
    Automatic Judge
    Coprime Sequence
  • 原文地址:https://www.cnblogs.com/panweiwei/p/14024689.html
Copyright © 2011-2022 走看看