当前位置:网站首页>Leetcode ugly number problem solution
Leetcode ugly number problem solution
2022-07-19 10:43:00 【Ellenjing】
background
I attended an interview at the beginning of the year , The first round was relatively smooth , I talked in English for nearly an hour about technology , Plus two coding subject . In the second round, I encountered a problem of finding ugly numbers , In fact, this problem is clearly done Leetcode The original title is , But I can't remember the specific idea , The result is very sad .
subject
The title is like this :
Give you an integer n , Please find out and go back to n individual Ugly number . Ugly number That is, only the prime factor is included 2、3 and / or 5 The positive integer .
I've been thinking a lot lately , There are two ways to solve :
1. Small cap pile
Ideas
Because it needs to be generated from small to large every time , So the first thought is that we can take advantage of the natural sorting feature of small top heap to take out the smallest ugly number in turn , Then multiply this number by the given prime factor to get the next ugly number , But in the process, the weight needs to be removed , That is, the current ugly number can only be multiplied by the number greater than or equal to the maximum prime factor of the ugly number to get the next ugly number .
Realization
public int nthUglyNumber(int n) {
PriorityQueue<Long> queue = new PriorityQueue<>();
int[] uglys = {
5, 3, 2};
queue.offer(1L);
long curr = 0;
while (n-- > 0) {
curr = queue.poll();
for (int ugly : uglys) {
queue.offer(curr * ugly);
if (curr % ugly == 0) break;// prune , duplicate removal
}
}
return (int) curr;
}
Complexity
Time complexity :O(nlogn)
Spatial complexity :O(n)
2. Dynamic programming
Ideas
In some scenes with many ugly numbers and prime factors , The method of small top heap will timeout , So we need a better method to achieve :
Array dp[i]: It means the first one i Ugly number ;
Array uglys[i]: Prime factors that generate ugly numbers ;
The next ugly number = min( Ugly number prime factor * An ugly number that has been generated ), So you need to define an array as a pointer to the generated ugly number ;
Array pointers[i]: Pointer to a generated ugly number in the ugly number generation sequence , Initialize to 0;
Array nums[i]: The next alternative set of ugly numbers , namely ,nums[i] = uglys[i] * dp[pointers[i]]; Each calculation results in nums, And select the smallest element from the set array ; Once the element is selected, it becomes the next ugly number , You need to update pointers[i]( Self increasing 1, Stands for pointing to the next ugly number ),nums[i] = uglys[i] * dp[pointers[i]];
The smallest ugly number is 1, take nums[i] Initialize to 1
Realization
public int nthUglyNumber(int n) {
long[] dp = new long[n + 1];
int[] uglys = {
5, 3, 2};
int[] pointers = new int[uglys.length];
long[] nums = new long[uglys.length];
Arrays.fill(nums, 1L);
for (int i = 1; i <= n; i++) {
long min = Arrays.stream(nums).min().getAsLong();
dp[i] = min;
for (int j = 0; j < uglys.length; j++) {
if (nums[j] == min) {
pointers[j]++;
nums[j] = dp[pointers[j]] * uglys[j];
}
}
}
return (int) dp[n];
}
Complexity
Time complexity :O(nm)
Spatial complexity :O(n + m)
m Is the number of ugly prime factors , Change the title to 3
3. Performance comparison
Then verify the comparison between the two methods , It can be seen that the memory consumption is basically the same , The performance improvement of dynamic planning is indeed very obvious :
replay
The small top of this question is of medium difficulty , Why didn't you even think clearly at that time ? Although the interview lasted for 3 Appear in hours , I feel my brain can't turn to comfort myself , But the root cause is that I was Leetcode When doing this problem , That is, just do it , Just want to make a quick decision , Didn't spend time thinking and analyzing , There are already debts . Today, we have found the solution of dynamic programming , Indeed, the performance has been improved a lot .
边栏推荐
- SAP AppGyver 的 Universal Theme System 使用介绍
- STL中stack和queue的使用以及模拟实现
- R language uses the KAP function of epidisplay package to calculate the proportion of calculation consistency of paired contingency tables and the value of kappa statistics, and uses xtabs function to
- 华为机试:报文解压缩
- SAP Fiori 的附件处理(Attachment handling)
- Brush questions with binary tree (2)
- Aike AI frontier promotion (7.17)
- Design of the multi live architecture in different places of the king glory mall
- How to use SVG to make text effects arranged along any path
- String type function transfer problem
猜你喜欢

因果学习将开启下一代AI浪潮?九章云极DataCanvas正式发布YLearn因果学习开源项目

从“被动”到“主动”,ZETA技术助力“RFID2.0”升级该如何实现?

智能存储柜控制系统设计及仿真

HCIA rip experiment 7.11

HCIA OSPF

Lvi-sam: laser IMU camera tight coupling mapping

双向NAT技术

c# treeView 树形结构递归处理(企业集团型层次树形展示)

Detailed explanation of C language custom types
![[Niuke swipe questions] / *c language realizes left-hand rotation of strings*/](/img/74/681975d85a671b4f75f2b392264105.png)
[Niuke swipe questions] / *c language realizes left-hand rotation of strings*/
随机推荐
LeetCode 2315. 统计星号(字符串)
R language uses the KAP function of epidisplay package to calculate the proportion of calculation consistency of paired contingency tables and the value of kappa statistics, and uses xtabs function to
如果是用mybatics去访问达梦数据库,相当于完全一样了?因为SQL语法没变。对吧?
机器学习模型的评估方法
SAP S4 Material Management 库存模块 MARD 数据库表读取技术细节介绍
知其然,而知其所以然,JS 对象创建与继承
R language uses LM function to build linear regression model, and uses subset function to specify the subset of data set to build regression model (uses subset function to filter the data subset that
C # treeview tree structure recursive processing (enterprise group type hierarchical tree display)
【Makefile】关于makefile使用上的一些备忘
R language ggplot2 visualization: use the gghistogram function of ggpubr package to visualize the grouping histogram, and use the palette parameter to customize the bar border color of the grouping hi
双向NAT技术
移植吴恩达深度学习01机器学习和神经网络第二周神经网络基础编程作业选修作业到pycharm
Effectively understand FreeSQL wheredynamicfilter and deeply understand the original design intention [.net orm]
Map遍历 key-value 的4种方法
开发第一个Flink应用
SAP AppGyver 的 Universal Theme System 使用介绍
[acwing] 60th weekly match b- 4495 Array operation
R language uses the ordinal of epidisplay package or. The display function obtains the summary statistical information of the ordered logistic regression model (the odds ratio and its confidence inter
创建虚拟机第一章(vmvare虚拟机)
win10开始键点击无响应