面试题34:丑数

package com.abuge;

public class GetUglyNum 
{
	//得到三个数的最小值
	public static int getMin(int num1, int num2, int num3)
	{
		int min = (num1 > num2) ? num2 : num1;
		
		min = (min > num3) ? num3 : min;
		return min;
	}
	
	//得到指定个丑数
	public static int getUglyNum(int index)
	{
		if(index <= 0)
		{
			return 0;
		}
		
		
		int[] uglyNumbers = new int[index];
		//初始化
		uglyNumbers[0] = 1;
		
		int currentIndex = 1;
		
		int mutiplyt2Index = 0;
		int mutiplyt3Index = 0;
		int mutiplyt5Index = 0;
		
		
		while(currentIndex < index)
		{
			int min = getMin(uglyNumbers[mutiplyt2Index] * 2, uglyNumbers[mutiplyt3Index] * 3, uglyNumbers[mutiplyt5Index] * 5);
			
			uglyNumbers[currentIndex] = min;
			
			//此时currentIndex指向当前最大的丑数,然后寻找到一个乘以2/3/5的使其刚好大于此时最大丑数的下一个丑数
			while(uglyNumbers[mutiplyt2Index] * 2 <= uglyNumbers[currentIndex])
			{
				mutiplyt2Index++;
			}
			
			while(uglyNumbers[mutiplyt3Index] * 3 <= uglyNumbers[currentIndex])
			{
				mutiplyt3Index++;
			}
			
			while(uglyNumbers[mutiplyt5Index] * 5 <= uglyNumbers[currentIndex])
			{
				mutiplyt5Index++;
			}
			
			currentIndex++;
		}
		
		return uglyNumbers[currentIndex - 1];
	}
	
	public static void main(String[] args)
	{
		System.out.println(getUglyNum(1));
		System.out.println(getUglyNum(2));
		System.out.println(getUglyNum(3));
		System.out.println(getUglyNum(4));
		System.out.println(getUglyNum(5));
		System.out.println(getUglyNum(6));
		System.out.println(getUglyNum(1500));
	}
}

你可能感兴趣的:(剑指offer,java相关)