劍指Offer-陣列-(9)
阿新 • • 發佈:2018-12-08
知識點/資料結構:陣列
題目描述:
把只包含質因子2、3和5的數稱作醜數(Ugly Number)。例如6、8都是醜數,但14不是,因為它包含質因子7。 習慣上我們把1當做是第一個醜數。求按從小到大的順序的第N個醜數。
這是用友的筆試題:AC了!很開心!
程式碼如下
public class Solution { public int GetUglyNumber_Solution(int index) { if(index<=0) {return 0;} int[] result = new int[index]; int count = 0; int a = 0; int b = 0; int c = 0; result[0] = 1; int tmp = 0; while (count < index-1) { tmp = min(result[a] * 2, min(result[b] * 3, result[c] * 5)); if(tmp==result[a] * 2) {a++;}//三條if防止值是一樣的,不要改成else的 if(tmp==result[b] * 3) {b++;} if(tmp==result[c]*5) {c++;} result[++count]=tmp; } return result[index - 1]; } private int min(int a, int b) { return (a > b) ? b : a; } }