Share my code[JAVA], 5ms


  • 0
    W
    public class Solution {
        public String getPermutation(int n, int k) {
            int[] n_ = {
                    1, 2, 6, 24, 120, 720, 5040, 40320, 362880
            };
            StringBuilder stringBuilder = new StringBuilder();
            List<Integer> numList = new ArrayList<Integer>();
            for (int i = 0 ; i <= n ; i++) {
                numList.add(i);
            }
    
            for (int i = n - 1 ; i >= 0 ; i--) {
                if (i == 0) {
                    stringBuilder.append(numList.get(1));
                    break;
                }
                int group = (int)Math.ceil((float)k / n_[i - 1]);
                int num = numList.get(group);
                numList.remove((Object)num);
                stringBuilder.append(num);
                k = k - n_[i - 1] * (group - 1);
            }
            return stringBuilder.toString();
        }
    }

  • 0
    H

    Can you please explain the logic ?


Log in to reply
 

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