Wins the Offer (thirty-three): Number of ugly
Search micro-channel public number: 'AI-ming3526' or 'this small computer vision' for more algorithms, machine learning, dry
CSDN: https://blog.csdn.net/baidu_31657889/
GitHub: https://github.com/ aimi-cn / AILearners
First, the primer
This series is my brush "to prove safety Offer" brush off the cattle in question notes online, it aims to enhance the ability under its own algorithm.
View the complete algorithm to prove safety issues resolved Offer Click CSDN and github link:
prove safety Offer complete analytical exercises CSDN address
github address
Second, the title
It contains only the number of prime factors 2, 3 and 5 is referred to as the number of ugly (Ugly Number). E.g. 6,8 are several ugly, but not 14, because it contains seven prime factors. Traditionally we have 1 as the first ugly number. Seeking ascending through N ugly large number sequence.
1, ideas
M is a number called number n of another factor, refers m divisible by n, i.e. n% m == 0. The definition of the ugly, ugly numbers 2, 3 and 5 can only be divisible. The definition of the ugly, ugly ugly number should be multiplied by another number 2, 3, or 5 (except 1). Therefore, we can create an array, which number is the number of ugly row good sequence, each number is the number of ugly ugly front multiplied by 2, 3 or 5 get.
The key problem with this idea is how to ensure that the number of ugly inside the array is sorted. For multiplied by 2, there is definitely a certain number of ugly T2, each of a number of ugly ahead of its results will be multiplied by 2 to get less than the maximum number has been ugly, ugly each number after it is multiplied by the multiplier 2 with the results obtained will be too large. We only need to remember the position of the lower number of ugly, but every time a new number is generated when the ugly, to update this T2. Multiplied by 3 and 5, the same also exists T3 and T5.
2, programming
python
Code implementation:
# -*- coding:utf-8 -*-
class Solution:
def GetUglyNumber_Solution(self, index):
# write code here
if index < 7:
return index
res = [1, 2, 3, 4, 5, 6]
# res[t2]=4 4*2=8 大于res里面4*1的值 res[t3]=3 3*3=9 大于res里面3*2的值 res[t5]=2 5*2=10 大于res里面5*1的值
t2, t3, t5 = 3, 2, 1
for i in range(6, index):
res.append(min(res[t2] * 2, res[t3] * 3, res[t5] * 5))
while res[t2] * 2 <= res[i]:
t2 += 1
while res[t3] * 3 <= res[i]:
t3 += 1
while res[t5] * 5 <= res[i]:
t5 += 1
return res[index - 1]
AIMI-CN AI learning exchange group [1015286623] for more information on AI
Sharing technology, fun in life: our number of public computer vision this small push "AI" series News articles per week, welcome your interest!