劍指offer-醜數(Java)__Java

來源:互聯網
上載者:User

題目描述
把只包含因子2、3和5的數稱作醜數(Ugly Number)。例如6、8都是醜數,但14不是,因為它包含因子7。 習慣上我們把1當做是第一個醜數。求按從小到大的順序的第N個醜數。

思路:
使用一個數組將之前已經求出來的醜數儲存起來,然後依次用2,3,5乘上數組中已經求出來的醜數,選出其中最小的一個儲存到數組中。假設數組中存的最大丑數是Max,那麼只要求出2,3,5乘以數組中的某一個數剛好比Max大,然後選出三者間最小的就可以。例如:當前數組中的醜數是:1,此時2*1,3*1,5*1,中最小的是2,將2存到數組中,此時數組中的數為1,2。Max=2,又因為2*1==Max,因此2乘的醜數應該為2*2,3*1>2,5*1>2,在新的4,3,5中最小的為3將3存到數組中,依次迴圈。

public class GetUglyNumber_Solution {    public static void main(String[] args) {        // TODO Auto-generated method stub        int index=11;        System.out.println(GetUglyNumber(index));    }    public static int GetUglyNumber(int index)    {        if(index==0)            return 0;            //如果index==0,返回0        int urgly[]=new int[index];        urgly[0]=1;        //當index。=0時將第一個醜數1放到數組中。        int urglyindex=1,min;        int nextindex2=0,nextindex3=0,nextindex5=0;        while(urglyindex<index)        {            min=urgly[nextindex2]*2<urgly[nextindex3]*3?urgly[nextindex2]*2:urgly[nextindex3]*3;            //min用於儲存新產生的大於當前數組最大值的最小丑數            min=min<urgly[nextindex5]*5?min:urgly[nextindex5]*5;            urgly[urglyindex]=min;            while(urgly[nextindex2]*2<=min)                nextindex2++;                //如果urgly[nextindex2]小於當前數組的最大值,nextindex2++;            while(urgly[nextindex3]*3<=min)                nextindex3++;                //如果urgly[nextindex3]小於當前數組的最大值,nextindex3++;                           while(urgly[nextindex5]*5<=min)                nextindex5++;                //如果urgly[nextindex5]小於當前數組的最大值,nextindex5++;            urglyindex++;            //urglyindex++;尋找下一個醜數        }     return urgly[index-1];    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.