剑指offer——丑数

来源:互联网 发布:软件工程软件测量过程 编辑:程序博客网 时间:2024/06/05 05:22

题目描述

把只包含因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。


思路:

取出的数一定是最小的,新的数 一定是比原队列中的所有数都要大的。

因为min一直在增大,然后min乘上的对应的数 也一直在增大,永远比队列中前面的值都要大。

import java.util.Queue;import java.util.LinkedList;public class Solution {    public int GetUglyNumber_Solution(int index) {        if(index==1)return 1; Queue<Integer>queue2 = new LinkedList<>(); Queue<Integer>queue3 = new LinkedList<>(); Queue<Integer>queue5 = new LinkedList<>(); queue2.offer(2);queue3.offer(3);queue5.offer(5); int count = 1; int min=0; while(count<index){  min = Math.min(Math.min(queue2.peek(), queue3.peek()), queue5.peek()); if(min==queue2.peek()){ queue2.offer(min*2); queue3.offer(min*3); queue5.offer(min*5); queue2.poll(); }else if (min==queue3.peek()) { queue3.offer(min*3); queue5.offer(min*5); queue3.poll();}else { queue5.offer(min*5); queue5.poll();} count++; }//while return min;    }}


原创粉丝点击