1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public class Solution { public int nthSuperUglyNumber( int n, int [] primeCollection) { if (primeCollection == null || primeCollection.length == 0 ) return 0 ; ArrayList<Integer> superUglyNumberCollection = new ArrayList<Integer>(); superUglyNumberCollection.add( 1 ); int [] lastNumberIndex = new int [primeCollection.length]; for ( int i = 2 ; i <= n; i++) { int possibleNumber = primeCollection[ 0 ] * superUglyNumberCollection.get(lastNumberIndex[ 0 ]); for ( int j = 1 ; j < primeCollection.length; j++) { possibleNumber = Math.min(possibleNumber, primeCollection[j] * superUglyNumberCollection.get(lastNumberIndex[j])); } superUglyNumberCollection.add(possibleNumber); for ( int j = 0 ; j < primeCollection.length; j++) { if (possibleNumber == primeCollection[j] * superUglyNumberCollection.get(lastNumberIndex[j])) { lastNumberIndex[j]++; } } } return superUglyNumberCollection.get(n- 1 ); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | public class Solution { public int nthSuperUglyNumber( int n, int [] primeCollection) { if (primeCollection == null || primeCollection.length == 0 ) return 0 ; ArrayList<Integer> superUglyNumberCollection = new ArrayList<Integer>(); superUglyNumberCollection.add( 1 ); int [] lastNumberIndex = new int [primeCollection.length]; for ( int i = 2 ; i <= n; i++) { int possibleNumber = primeCollection[ 0 ] * superUglyNumberCollection.get(lastNumberIndex[ 0 ]); for ( int j = 1 ; j < primeCollection.length; j++) { possibleNumber = Math.min(possibleNumber, primeCollection[j] * superUglyNumberCollection.get(lastNumberIndex[j])); } superUglyNumberCollection.add(possibleNumber); for ( int j = 0 ; j < primeCollection.length; j++) { if (possibleNumber == primeCollection[j] * superUglyNumberCollection.get(lastNumberIndex[j])) { lastNumberIndex[j]++; break ; //This doesn't account for duplicates } } } return superUglyNumberCollection.get(n- 1 ); } } |
No comments:
Post a Comment