【數組】Next Permutation

題目:html

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.函數

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).spa

The replacement must be in-place, do not allocate extra memory.code

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1htm

思路:blog

步驟以下:get

  • 從最尾端開始往前尋找兩個相鄰的元素,二者知足i < ii(令第一個元素爲i,第二個元素爲ii)
  • 若是沒有找到這樣的一對元素則,代表當前的排列是最大的,沒有下一個大的排列
  • 若是找到,再從末尾開始找出第一個大於i的元素,記爲j                                  本文地址
  • 交換元素i, j,再將ii後面的全部元素顛倒排列(包括ii)
  • 若是某個排列沒有比他大的下一個排列(即該排列是遞減有序的),調用這個函數仍是會把原排列翻轉,即獲得最小的排列
var nextPermutation = function(nums) {
        var len=nums.length;
        if(len<=1){
            return;
        }

        for(var i=len-2,j=len-1;i>=0;i--,j--){
            if(nums[i]<nums[j]){
                var q=len-1;
                while(nums[q]<=nums[i]){
                    q--;
                }
                var temp=nums[i];
                nums[i]=nums[q];
                nums[q]=temp;
                var a=nums.splice(q).reverse()
                nums=nums.concat(a);
                break;
            }
        }
        if(i==-1){
            nums.reverse();
        }
};
相關文章
相關標籤/搜索