zoukankan      html  css  js  c++  java
  • python 练习题 NC97 字符串出现次数的TopK问题

    地址:https://www.nowcoder.com/practice/fd711bdfa0e840b381d7e1b82183b3ee?tpId=188&&tqId=38637&rp=1&ru=/activity/oj&qru=/ta/job-code-high-week/question-ranking

     1 '''
     2 描述
     3 给定一个字符串数组,再给定整数k,请返回出现次数前k名的字符串和对应的次数。
     4 返回的答案应该按字符串出现频率由高到低排序。如果不同的字符串有相同出现频率,按字典序排序。
     5 对于两个字符串,大小关系取决于两个字符串从左到右第一个不同字符的 ASCII 值的大小关系。
     6 比如"ah1x"小于"ahb","231"<”32“
     7 字符仅包含数字和字母
     8 
     9 [要求]
    10 如果字符串数组长度为N,时间复杂度请达到O(N log K)O(NlogK)
    11 
    12 示例1
    13 输入:
    14 ["a","b","c","b"],2
    15 复制
    16 返回值:
    17 [["b","2"],["a","1"]]
    18 说明:
    19 "b"出现了2次,记["b","2"],"a"与"c"各出现1次,但是a字典序在c前面,记["a","1"],最后返回[["b","2"],["a","1"]]
    20  
    21 示例2
    22 输入:
    23 ["123","123","231","32"],2
    24 返回值:
    25 [["123","2"],["231","1"]]
    26 说明:
    27  "123"出现了2次,记["123","2"],"231"与"32"各出现1次,但是"231"字典序在"32"前面,记["231","1"],最后返回[["123","2"],["231","1"]] 
    28 
    29 '''
    30 
    31 '''
    32 1.先计数并存转成list格式
    33 2.先按照 出现数字降序 再按照字符升序排序
    34 '''
    35 
    36 #
    37 # return topK string
    38 # @param strings string字符串一维数组 strings
    39 # @param k int整型 the k
    40 # @return string字符串二维数组
    41 #
    42 class Solution:
    43     def topKstrings(self , strings , k ):
    44         # write code here
    45         res = {}
    46         for i in strings:
    47             if i not in res.keys():
    48                 res[i] = 1
    49             else:
    50                 res[i] +=1
    51         resList = []
    52         for i in res.keys():
    53             resList.append([i,res[i]])
    54         resList.sort(key=lambda i : (-i[1],i[0]))
    55         return resList[:k]
  • 相关阅读:
    android Logger 一二三
    深挖android low memory killer
    ios CoreBluetooth 警告 is being dealloc'ed while pending connection
    iOS 国际化多语言设置 xcode7
    iOS 控制单个控制器旋转
    ios 开发 收起键盘的小技巧
    xcode ___gxx_personality_v0" 编译错误
    xcode6 AsynchronousTesting 异步任务测试
    xcode6 framework missing submodule xxx 警告
    iOS AVCaptureVideoDataOutputSampleBufferDelegate 录制视频
  • 原文地址:https://www.cnblogs.com/whycai/p/15143398.html
Copyright © 2011-2022 走看看