?LeetCode刷題實(shí)戰(zhàn)31:下一個排列
算法的重要性,我就不多說了吧,想去大廠,就必須要經(jīng)過基礎(chǔ)知識和業(yè)務(wù)邏輯面試+算法面試。所以,為了提高大家的算法能力,這個公眾號后續(xù)每天帶大家做一道算法題,題目就從LeetCode上面選 !
今天和大家聊的問題叫做下一個排列,我們先來看題面:
https://leetcode-cn.com/problems/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 and use only constant extra memory.
題意
樣例
一些例子,輸入位于左側(cè)列,其相應(yīng)輸出位于右側(cè)列。
1,2,3?→?1,3,23,2,1?→?1,2,31,1,5?→?1,5,1
題解
public?class?Solution?{
?
??public?void?nextPermutation(int[] nums)?{
????int?n = nums.length;
????int?i = n - 1;
????for(; i >= 1; i--) {
??????if(nums[i] > nums[i - 1]) {
????????break;
??????}
????}
????if(i >= 1) {
??????int?j = n - 1;
??????for(; j >= i; j--) {
????????if(nums[j] > nums[i - 1]) {
??????????break;
????????}
??????}
??????swap(i - 1, j, nums);
??????reverse(nums, i);
????}else?{
??????reverse(nums, 0);
????}
??}
??
??private?void?reverse(int[] nums, int?index)?{
????int?i = index;
????int?j = nums.length - 1;
????while(i < j) {
??????swap(i, j, nums);
??????i++;
??????j--;
????}
??}
?
??private?void?swap(int?i, int?j, int[] nums)?{
????int?temp = nums[i];
????nums[i] = nums[j];
????nums[j] = temp;
??}
}
上期推文:
