172. Factorial Trailing Zeroes
題目簡介:給定一個數n,求n!的結尾連續的0的個數。
解題思路:通過觀察可得,0只可能由2和5相乘獲得,而5的個數總是小於等於2的個數,所以問題就轉爲了尋找n!中因子5的個數。代碼如下:
class Solution(object):
def trailingZeroes(self, n):
"""
:type n: int
:rtype: int
"""
count = 0
while n:
count+=int(n/5)
n = int(n/5)
return count
204. Count Primes
題目簡介:求解小於n的質數的個數。
解題思路:利用leetcode提供的hints可得到一種快速的解法。代碼如下:
import math
class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
if n < 3:
return 0
count = 0
numberBook = [1]*n
numberBook[0] = 0
numberBook[1] = 0
for i in range(2,int(math.sqrt(n)+1)):
if numberBook[i] and self.checkPrime(i):
t = i
while (t*i < n):
numberBook[t*i] = 0
t+=1
return sum(numberBook)
def checkPrime(self,n):
for i in range(2,int(math.sqrt(n)+1)):
if n % i == 0:
return False
return True
453. Minimum Moves to Equal Array Elements
題目簡介:對含有n個元素的數組,每次對n-1個數加1,直到最後所有數都相等。求需要加1的最少次數。
解題思路:易知,不被加1的數肯定是當前數組裏的最大值。因此,可以反向思考,要對除了最大值以外的所有數加1,就相當於把最大值減1,而其他數不變。此題也就轉化爲了,其餘各個數與最小值的差值爲多少。代碼如下:
class Solution(object):
def minMoves(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sum(nums)-len(nums)*min(nums)