当前位置:网站首页>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];
}
}
边栏推荐
猜你喜欢
随机推荐
走进通信:为什么4G信号满格,却上不了网呢
Share 14 JS functions you must know
Mock模拟数据,并发起get,post请求(保姆级教程,一定能成功)
cdc抽取mysql整个实例的binlog,有没有方案通过配置的方式将这些库表拆开分发到kafka
CC2530_ZigBee+HUAWEI CLOUD IOT: Design your own cold chain acquisition system
注意力机制的详细理解
yaml数据格式
目标检测-YOLOv3理论讲解
Cool open technology x StarRocks: unified OLAP analysis engine, comprehensive building digital model of OTT
【牛客在线OJ】-字符逆序
AI智能剪辑,仅需2秒一键提取精彩片段
Cyanine5.5 alkyne|Cy5.5 alkyne|1628790-37-3|Cy5.5-ALK
【刻意练习观后管】刻意练习
yaml data format
xxl-job 实现email发送警告的代码解析(一行一行代码解读)
【汇编语言02】第2章 寄存器——理论知识
细胞不可渗透的荧光探针 锌离子荧光探针Zinquin 151606-29-0
大佬们,flinkcdc 2.2 版本采集sqlserver只能采集到全量的数据,不能采集到增量的数
rhel8.3 系统下修改有线网卡配置信息实现联网
高等数学---第十章无穷级数---常数项级数









