LintCodet题目

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
    ""
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值