3. 统计数字
中文English
计算数字 k 在 0 到 n 中的出现的次数,k 可能是 0~9 的一个值。
样例
样例 1:
输入:
k = 1, n = 1
输出:
1
解释:
在 [0, 1] 中,我们发现 1 出现了 1 次 (1)。
样例 2:
输入:
k = 1, n = 12
输出:
5
解释:
在 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] 中,我们发现 1 出现了 5 次 (1, 10, 11, 12)(注意11中有两个1)。
"""
@param k: An integer
@param n: An integer
@return: An integer denote the count of digit k in 1..n
"""
def digitCounts(self, k, n):
# write your code here
result = 0
for item in range(0, n+1):
count_tmp = str(item).count(str(k))
result += count_tmp
return result
count() 方法用于统计字符串里某个字符出现的次数。
str.count(sub, start= 0,end=len(string))
46. 主元素
中文English
给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。
样例
样例 1:
输入: [1, 1, 1, 1, 2, 2, 2]
输出: 1
样例 2:
输入: [1, 1, 1, 2, 2, 2, 2]
输出: 2
挑战
要求时间复杂度为O(n),空间复杂度为O(1)
注意事项
你可以假设数组非空,且数组中总是存在主元素。
(1)对立面的元素依次计数,取最大值。
class Solution:
"""
@param: nums: a list of integers
@return: find a majority number
"""
def majorityNumber(self, nums):
# write your code here
max_nums = nums[0]
max_ = nums.count(0)
for i in nums:
a = nums.count(i)
if a > max_:
max_ = a
max_nums = i
return max_nums
(2)摩尔投票法
https://blog.csdn.net/happyeveryday62/article/details/104136295
.
class Solution:
"""
@param: nums: a list of integers
@return: find a majority number
""