The number of ugly questions in Java---face

Source: Internet
Author: User

Time limit: 1 seconds Space limit: 32768K Topic Description The number that contains only the factors 2, 3, and 5 is called the Ugly number (Ugly numbers). For example, 6, 8 are ugly numbers, but 14 is not, because it contains factor 7. We used to think of 1 as the first ugly number. Find the nth ugly number in order from small to large.
Import Java.util.arraylist;public class Solution {public int getuglynumber_solution (int index) {/* timed out:        int ugly=0;        int COUNT=1;//1 is the first ugly number int n=2;            while (Count<index) {if (ifugly (n)) {count++;        } n++;    } return N;        } public boolean ifugly (int num) {while (num%2==0) num/=2;        while (num%3==0) num/=3;        while (num%5==0) num/=5;        if (num==1) {return true;        }else {return false; }    }*/


if (index<=0) return 0; Arraylist<integer> list=new arraylist<integer> (); List.add (1); int m2=0; int m3=0; int m5=0; while (List.size () <index) {int I2=list.get (m2) * *; int I3=list.get (m3); int I5=list.get (M5); int Min=math.min (I2,math.min (I3,I5)); List.add (min); if (MIN==I2) {m2++; } if (Min==i3) {m3++; } if (min==i5) {m5++; }} return List.get (List.size ()-1); } }

The first feeling can also run the results, but because each number has been calculated, so the system detection display algorithm timed out, that is, the same test case time more than 1s, it feels a bit strange. It's not so exaggerated.

The second is based on the definition of the ugly number, an ugly number is definitely another ugly multiply 2,3,5 results, so we can create an array to save the ugly number found, and then the key is how to ensure that the array is sorted, here compare the size of each multiplication m2,m3,m5, The array inside this operation is definitely ordered, so that it can be output directly at the end.

Save the found number of ugly, use space to change time. This algorithm takes 32ms of time.

The number of ugly questions in Java---face

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.