LeetCode[264] Ugly Number II

来源:互联网 发布:新剑侠情缘mac下载 编辑:程序博客网 时间:2024/05/23 12:34

Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number.

每次只选一个元素加入数组中,同时记录下一个可能填入数组中的元素

class Solution {public:int nthUglyNumber(int n) {int* uglyNum = new int[n];uglyNum[0] = 1;int* ptr_2 = uglyNum, *ptr_3 = uglyNum, *ptr_5 = uglyNum;for (int i = 1; i < n; i++){uglyNum[i] = min(*ptr_2 * 2, *ptr_3 * 3, *ptr_5 * 5);if (uglyNum[i] == *ptr_2 * 2)ptr_2++;if (uglyNum[i] == *ptr_3 * 3)ptr_3++;if (uglyNum[i] == *ptr_5 * 5)ptr_5++;}return uglyNum[n - 1];}int min(int a, int b, int c){int temp = a < b ? a : b;return temp < c ? temp : c;}};

0 0
原创粉丝点击