日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Leetcode--264. 丑数Ⅱ

發(fā)布時(shí)間:2024/7/19 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Leetcode--264. 丑数Ⅱ 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

編寫一個(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ù)。
說明:??

1?是丑數(shù)。
n?不超過1690。

思路:從1開始,需要對每個(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. 丑数Ⅱ的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。