JavaScript Solution with Question


  • 0
    I

    At the beginning I didn't even understand the question. After some searching, I found this link solution

    I followed the steps provided in this article, and passed the test. But why? Why through these steps we can get the lexicographically next greater permutation of numbers?

    var nextPermutation = function(nums) {
        
        var index, numsLen;
        
        function reverse (start, end) {
            var temp;
            while (start < end) {
                temp = nums[start];
                nums[start] = nums[end];
                nums[end] = temp;
                start++;
                end--;
            }
        }
        
        if (!nums || nums.length < 1) {
            return;
        }
        
        numsLen = nums.length
        
        for (index = numsLen - 1; index > 0; index--) {
            if (nums[index - 1] < nums[index]) {
                for (var n = numsLen - 1; n >= index; n--) {
                    if (nums[n] > nums[index - 1]) {
                        var temp = nums[n];
                        nums[n] = nums[index - 1];
                        nums[index - 1] = temp;
                        break;
                    }
                }
                break;
            }
            
        }
        
        reverse(index, numsLen-1);
        
    };

Log in to reply
 

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