Next Permutation


//this is my solution
int lens = nums.length;
int temp = 0;
int start = 0;// 从第几个元素开始升序排列
boolean isPossible = true;
if (lens > 0) {
for (int i = lens  1; i >= 0; i) {
if (isPossible) {
for (int j = lens  1; j > i; j) {
if (nums[j] > nums[i]) {//find the position to reverse
temp = nums[j];
nums[j] = nums[i];
nums[i] = temp;
start = i;//Record this position
isPossible = false;
break;
}
}
}} } if (isPossible) { for (int i = 0; i < (lens+1 )/ 2; i++) {//reverse nums temp = nums[lens  i  1]; nums[lens  i  1] = nums[i]; nums[i] = temp; } } else {//reverse nums form start+1 to the end for (int i = start + 1; i < (lens + start + 1) / 2; i++) { temp = nums[i]; nums[i] = nums[lens + start  i]; nums[lens + start  i] = temp; } }

The while loop condition on 'j' can be changed to "j >= i+1" since we do not need to traverse all the way back to j>=0 as we need to find the first larger element to the right of "i1". Moreover, nums[i] > nums[i1] due to the previous for loop and when the while loop breaks, the correctness is not affected.

@shraddheshb. Well, the while loop will end before it reaches ''i'' any way, so it does not make a diffrence in runtime.