Given an array nums of integers, return how many of them contain an even number of digits.
Example 1:
1 2 3 4 5 6 7 8 9
Input: nums = [12,345,2,6,7896] Output: 2 Explanation: 12 contains 2 digits (even number of digits). 345 contains 3 digits (odd number of digits). 2 contains 1 digit (odd number of digits). 6 contains 1 digit (odd number of digits). 7896 contains 4 digits (even number of digits). Therefore only 12 and 7896 contain an even number of digits.
Example 2:
1 2 3 4
Input: nums = [555,901,482,1771] Output: 1 Explanation: Only 1771 contains an even number of digits
Constraints:
1 <= nums.length <= 500
1 <= nums[i] <= 10^5
解题
思路:题目的关键点在于如何计数一个整数的位数。Hint给出的方法是:Divide the number by 10 again and again to get the number of digits。我想到的是把整数转化为string类型,因为python种字符串类型是可迭代的,可以直接用len()计数位数。
我的代码:
1 2 3 4 5 6 7
classSolution(object): deffindNumbers(self, nums): sum = 0 for num in nums: iflen(str(num))%2 == 0: sum += 1 returnsum
别人更简洁的代码:
1 2 3
classSolution(object): deffindNumbers(self, nums): returnsum(len(str(n)) % 2 == 0for n in nums)
You’re given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.
The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A".
Example 1:
1 2
Input: J = "aA", S = "aAAbbbb" Output: 3
Example 2:
1 2
Input: J = "z", S = "ZZ" Output: 0
Note:
S and J will consist of letters and have length at most 50.
classSolution(object): defnumJewelsInStones(self, J, S): """ :type J: str :type S: str :rtype: int """ sum = 0 for j in J: count = S.count(j) sum += count returnsum # Runtime: 12 ms # Memory Usage: 11.9 MB
从答案中找到了一些很简洁的解决办法:
1 2 3 4 5 6 7 8 9
defnumJewelsInStones(self, J, S): returnsum(map(J.count, S)) defnumJewelsInStones(self, J, S): returnsum(map(S.count, J)) defnumJewelsInStones(self, J, S): returnsum(s in J for s in S) defnumJewelsInStones(self, J, S): J = set(J) returnsum([1for stone in S if stone in J])
但是似乎运行时间和内存占用比不比我第一次提交的代码小。
总结
代码的简洁度固然重要,但是Time and space complexity(时空复杂度)应该排在第一位。
map函数
1
map(function, iterable, ...)
map() 会根据提供的函数对指定序列做映射。第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。
Cannot complete the install because one or more required items could not be found. Software currently installed: MercurialEclipse 2.5.2.201806082050 (mercurialeclipse.feature.group 2.5.2.201806082050) Missing requirement: MercurialEclipse 2.5.2.201806082050 (com.vectrace.MercurialEclipse 2.5.2.201806082050) requires 'bundle org.eclipse.jface.text 3.11.0' but it could not be found Cannot satisfy dependency: From: MercurialEclipse 2.5.2.201806082050 (mercurialeclipse.feature.group 2.5.2.201806082050) To: com.vectrace.MercurialEclipse [2.5.2.201806082050]