package no1_50;
public class subject031 {
class Solution {
public void nextPermutation(int[] nums) {
int len = nums.length;
if(len<=1) return ;
int index1 = len-2 ; //第一个逆序数
int index2 = len-1 ; //第一个比逆序数大的数
int temp =0;
while(index1>=0) {
if(nums[index1] <nums[index1+1]) {
break;
}else {
index1--;
}
}
if(index1==-1) {//如果是最大的数,全部逆序,然后返回
reverse(nums, 0);
return;
}
while(index2>index1&&index2>=0) {
if(nums[index2] > nums[index1]) {
break;
}else {
index2--;
}
}
temp = nums[index1];
nums[index1] = nums[index2];
nums[index2] = temp ;
reverse(nums, index1+1);
}
public void reverse(int[] nums, int start) {
int l = start, r = nums.length -1 ;
int temp = 0;
while(l<r) {
temp = nums[l];
nums[l] = nums[r];
nums[r] = temp;
l++;
r--;
}
}
}
public static void main(String[] args) {
subject031 subject = new subject031();
Solution s = subject.new Solution();
int[] nums = {2, 1, 3, 4};
//int[] nums = {1,1};
for(int i=0; i<nums.length;i++) {
System.out.print(nums[i] + "\t");
}
System.out.println();
s.nextPermutation(nums);
System.out.println("=================");
for(int i=0; i<nums.length;i++) {
System.out.print(nums[i] + "\t");
}
}
}
leetcode 31
于 2019-05-08 13:12:57 首次发布