java 13ms beats 99.53%


  • 0
    public class Solution {
        
        public String getPermutation(int n, int k) {
            if (n == 0) {
                return "";
            }
            int[] mark = new int[n];
            StringBuilder sb = new StringBuilder();
            mark[0] = 1;
            for (int i = 1; i < n; i++) {
                mark[i] = (i + 1) * mark[i - 1];
            }
            boolean[] used = new boolean[n];
            int len = n;
            for (int i = 0 ; i < n; i++) {
                int num = (k - 1) / (mark[n - 1 - i] / len) + 1;
                k = (k - 1)% (mark[n - 1 - i] / len) + 1;
                len--;
                int count = 0;
                for (int j = 0; j < n; j++) {
                    if (used[j]) {
                        continue;
                    }
                    count++;
                    if(count == num) {
                        sb.append(j + 1);
                        used[j] = true;
                        break;
                    }
                }
                
            }
            return sb.toString();
        }
    }
    

Log in to reply
 

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