Next Permutation



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).

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

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,1


題意:給定一串數字,根據字典序求出下一個字符串;若是不存在下一個,則從小到大輸出

思路:字典序排序的最終結果是字符從大到小排列,首先從後往前掃描,找到第一組i,j,使i<j&&num[i]<num[j]。若是不存在,則表示該串以排序完畢,則從小到大排序結束算法。不然,再從後往前掃描,找到第一個num[k]>num[i],兩數交換。而後從j開始到字符串末尾進行反轉,排序完畢,結束算法。

實現java

public class Solution {
    public void nextPermutation(int[] num) {
        int l=num.length;
        boolean flag=false;
        for(int j=l-1,i=j-1;!flag&&i>=0;j--,i=j-1){//從右往左尋找是否存在i<j&&num[i]<num[j]
             if(num[i]<num[j]){//若是存在i<j&&num[i]<num[j]
                  flag=true;
                  for(int k=l-1;k>i;k--){//從右往左尋找第一個比num[i]大的數
                       if(num[k]>num[i]){//兩數交換
                            int temp=num[k];
                            num[k]=num[i];
                            num[i]=temp;
                            break;
                       }
                  }
                  for(int k=j,t=l-1;k<t;k++,t--){//從j開始到數組最後一個元素反轉
                       int temp=num[k];
                       num[k]=num[t];
                       num[t]=temp;
                  }
             }
        }
        if(!flag){//若是不存在i<j&&num[i]<num[j],表示該序列爲最後一個序列,則從小到大排列
             Arrays.sort(num);
        }
    }
}
相關文章
相關標籤/搜索