5ms JAVA solution. [Help] How to get it faster

  • 0

    I have to store n! from 1 to 8 in an array.
    If i use another method to calculate n!, it will exceed the time limit.
    Please help to make this faster.


    public class Solution {
        public String getPermutation(int n, int k) {
            int[] numPer = {0,1,2,6,24,120,720,5040,40320};
            ArrayList<Integer> l = new ArrayList<>();
            for(int i = 1; i<n+1; i++) l.add(i);
            StringBuffer s = new StringBuffer();
            for(int i=n; i>1; i--){
                int first = (int)Math.floor((double)(k-1) / (double)numPer[i-1]);
                k = k - first * numPer[i-1];
                s.append( l.get(first));
            return s.toString();

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.