LeetCode1295. 统计位数为偶数的数字

一. 题目
  1. 题目
    给你一个整数数组 nums,请你返回其中位数为 偶数 的数字的个数。
  2. 示例
    LeetCode1295. 统计位数为偶数的数字_第1张图片
二. 方法一
  1. 解题思路
    将数字转成字符, 然后判断长度即可

  2. 解题代码

    def findNumbers(self, nums: List[int]) -> int:
        count = 0
        for ele in nums:
            if len(str(ele)) % 2 == 0:
                count += 1
        return count
    
  3. 分析
    时间复杂度: O(n)
    空间复杂度: O(1)

三. 方法二: 方法一的变形
  1. 解题思路

  2. 解题代码

    def findNumbers(self, nums: List[int]) -> int:
        return sum(1 for ele in nums if len(str(ele)) % 2 == 0)
    
  3. 分析:
    时间复杂度: O(n)
    空间复杂度: O(1)

你可能感兴趣的:(leetcode,列表)