Leetcode--264. 丑数Ⅱ
編寫(xiě)一個(gè)程序,找出第 n 個(gè)丑數(shù)。
丑數(shù)就是只包含質(zhì)因數(shù)?2, 3, 5 的正整數(shù)。
示例:
輸入: n = 10
輸出: 12
解釋: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 個(gè)丑數(shù)。
說(shuō)明:??
1?是丑數(shù)。
n?不超過(guò)1690。
思路:從1開(kāi)始,需要對(duì)每個(gè)值都乘以2,3,5,然后判斷大小把他們依次放入數(shù)組
設(shè)置三個(gè)指針位,各自獨(dú)立地向后遍歷,實(shí)現(xiàn)這個(gè)目標(biāo)
提交的代碼:
class Solution {
? ? public int nthUglyNumber(int n) {
? ? ? ? int x,y,z,i,j=1;
? ? ? ? int[] nums = new int[1690];
? ? ? ? nums[0] = 1;
? ? ? ? x = 0;
? ? ? ? y = 0;
? ? ? ? z = 0;
? ? ? ? for(i=1;i<n;i++)
? ? ? ? {
? ? ? ? ?? ?j = java.lang.Math.min(nums[x]*2, java.lang.Math.min(nums[y]*3,nums[z]*5));
? ? ? ? ?? ?if(nums[x]*2==j)
? ? ? ? ?? ?{
? ? ? ? ?? ??? ?nums[i]=j;
? ? ? ? ?? ??? ?x++;
? ? ? ? ?? ?}
? ? ? ? ?? ?if(nums[y]*3==j)? ? //不可用else if,否則如果x位于第三個(gè)位置3處,y位于第二個(gè)位置2處,會(huì)出現(xiàn)重復(fù)的數(shù)字(2*3=3*2)
? ? ? ? ?? ?{
? ? ? ? ?? ??? ?nums[i]=j;
? ? ? ? ?? ??? ?y++;
? ? ? ? ?? ?}
? ? ? ? ?? ?if(nums[z]*5==j)
? ? ? ? ?? ?{
? ? ? ? ?? ??? ?nums[i]=j;
? ? ? ? ?? ??? ?z++;
? ? ? ? ?? ?} ? ?? ?
? ? ? ? }
? ? ? ? return nums[n-1];
? ? }
}
完整的代碼:
import java.util.Scanner;
public class Soluiton264 {
? ? public static int nthUglyNumber(int n) {
? ? ? ? int x,y,z,i,j=1;
? ? ? ? int[] nums = new int[1690];
? ? ? ? nums[0] = 1;
? ? ? ? x = 0;
? ? ? ? y = 0;
? ? ? ? z = 0;
? ? ? ? for(i=1;i<n;i++)
? ? ? ? {
? ? ? ? ?? ?j = java.lang.Math.min(nums[x]*2, java.lang.Math.min(nums[y]*3,nums[z]*5));
? ? ? ? ?? ?if(nums[x]*2==j)
? ? ? ? ?? ?{
? ? ? ? ?? ??? ?nums[i]=j;
? ? ? ? ?? ??? ?x++;
? ? ? ? ?? ?}
? ? ? ? ?? ?if(nums[y]*3==j)
? ? ? ? ?? ?{
? ? ? ? ?? ??? ?nums[i]=j;
? ? ? ? ?? ??? ?y++;
? ? ? ? ?? ?}
? ? ? ? ?? ?if(nums[z]*5==j)
? ? ? ? ?? ?{
? ? ? ? ?? ??? ?nums[i]=j;
? ? ? ? ?? ??? ?z++;
? ? ? ? ?? ?} ? ?? ?
? ? ? ? }
? ? ? ? return nums[n-1];
? ? }
?? ?public static void main(String[] args)
?? ?{
?? ??? ?Scanner scanner = new Scanner(System.in);
?? ??? ?int x = scanner.nextInt();
?? ??? ?System.out.println(nthUglyNumber(x));
?? ?}
}
?
總結(jié)
以上是生活随笔為你收集整理的Leetcode--264. 丑数Ⅱ的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 牛客网--19校招--获得最多的奖金
- 下一篇: 【剑指offer】面试题09:用两个栈实