31. Next Permutation

 

Example 1:

Input: nums = [1,2,3]
Output: [1,3,2]

Example 2:

Input: nums = [3,2,1]
Output: [1,2,3] 
 
class Solution {
public void nextPermutation(int[] nums) {
int pivot = -1;
int n = nums.length;
for(int i = n-2;i >=0 ;i--){
if(nums[i] < nums[i+1]){
pivot = i;
break;
}
}
if(pivot == -1){
reverse(nums,0,n-1);
return;
}
for(int i = n-1;i > pivot;i--){
if(nums[pivot] < nums[i]){
swap(nums,pivot,i);
break;
}
}
reverse(nums,pivot+1,n-1);
}
public void reverse(int nums[], int start,int end){
while(start < end){
swap(nums,start++,end--);
}
}
public void swap(int nums[], int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
 

Comments

Popular Posts