当前位置:网站首页>2022/08/02------Ugly number
2022/08/02------Ugly number
2022-08-03 18:09:00 【city pig】
题目描述
解题思路
解题思路一:Make judgments while increasing numbers,Make the most of the ugly numbers you saved earlier.缺点:超出时间限制.
优化思路:It should not be judged numerically one by one,To take full advantage of the big ugly numbers are composed of the clown numbers,to get beforenThe specific value of the number.Avoid useless judgments,优化时间效率.
代码实现
思路一代码实现:
package cz;
import java.util.ArrayList;
import java.util.List;
public class NthUglyNumber_0802 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int n=11;
System.out.print(nthUglyNumber(n));
}
public static int nthUglyNumber(int n) {
List<Integer> mlist=new ArrayList<>();
int count=1;
int res=1;
mlist.add(res);
while(true) {
if(count==n)break;
else {
res+=1;
if(res%2==0&&mlist.contains(res/2)||res%3==0&&mlist.contains(res/3)||res%5==0&&mlist.contains(res/5)) {
count++;
mlist.add(res);
}
}
}
return res;
}
}
The optimization idea code is implemented as follows:
package cz;
import java.util.ArrayList;
import java.util.List;
public class NthUglyNumber_0802 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int n=11;
System.out.print(nthUglyNumber(n));
}
public static int nthUglyNumber(int n) {
int[] ugly=new int [n];
ugly[0]=1;
int i=0,j=0,k=0;
for(int index=1;index<n;index++)
{
int temp=Math.min(ugly[i]*2, Math.min(ugly[j]*3, ugly[k]*5));
//避免重复
if(temp==ugly[i]*2)i++;
if(temp==ugly[j]*3)j++;
if(temp==ugly[k]*5)k++;
ugly[index]=temp;
}
return ugly[n-1];
}
}
边栏推荐
猜你喜欢
【用户运营】用这4个最佳客户服务策略,减少客户流失率
LeetCode - 102. 二叉树的层序遍历;110. 平衡二叉树;098. 验证二叉搜索树
mysql之数据库账户管理与优化
rhel8.3 系统下修改有线网卡配置信息实现联网
图像质量指标:PSNR、SSIM、MSE
CC2530_ZigBee+HUAWEI CLOUD IOT: Design your own cold chain acquisition system
荧光标记多肽FITC/AMC/FAM/Rhodamine/TAMRA/Cy3/Cy5/Cy7-Peptide
Higher mathematics - chapter ten infinite series - constant term series
openresty 高可用部署
InnoDB 中不同SQL语句设置的锁
随机推荐
【刻意练习观后管】刻意练习
es6新增-Promise详解(异步编程的解决方案1)
LyScript 内存交换与差异对比
云图说丨初识华为云微服务引擎CSE
EasyNTS上云网关断电重启后设备离线是什么原因?
Unable to start SinkRunner: { policy:org.apache.flume
开篇-开启全新的.NET现代应用开发体验
WPF implements column chart
China Hashpower Conference Ascension Kunpeng Ecological Forum was held; Kuaishou established an independent to B business department…
超T动力 焕“芯”出发 | 中国重汽专属定制版WP14T产品闪耀登场
域名抢注“卷”到了表情包?ENS逆势上涨的新推力
【Deliberately practice the view of the back tube】deliberately practice
Postgresql 备份大小情况!
【牛客在线OJ】-字符逆序
xxl-job 实现email发送警告的代码解析(一行一行代码解读)
软件盘点企业使用服装ERP的好处
使用range-based for循环的注意事项
【JS】利用JS给删除按钮添加提示框
PHP基础笔记-NO.2
基于PHP7.2+MySQL5.7的回收租凭系统