Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 9d4b55b

Browse files
authored
Update Next Permutation.java
1 parent 7956534 commit 9d4b55b

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

Medium/Next Permutation.java

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,7 @@
11
class Solution {
22
public void nextPermutation(int[] nums) {
3-
if (nums.length <= 1) {
4-
return;
5-
}
63
int idx = nums.length - 2;
7-
while (idx >= 0 && nums[idx] >= nums[idx + 1]) {
4+
while (idx >= 0 && nums[idx + 1] <= nums[idx]) {
85
idx--;
96
}
107
if (idx >= 0) {
@@ -14,16 +11,21 @@ public void nextPermutation(int[] nums) {
1411
}
1512
swap(nums, idx, endIdx);
1613
}
17-
int startIdx = idx + 1;
14+
reverse(nums, idx + 1);
15+
}
16+
17+
private void reverse(int[] nums, int startIdx) {
1818
int endIdx = nums.length - 1;
1919
while (startIdx < endIdx) {
20-
swap(nums, startIdx++, endIdx--);
20+
swap(nums, startIdx, endIdx);
21+
startIdx++;
22+
endIdx--;
2123
}
2224
}
2325

24-
private void swap(int[] nums, int idxOne, int idxTwo) {
25-
int temp = nums[idxOne];
26-
nums[idxOne] = nums[idxTwo];
27-
nums[idxTwo] = temp;
26+
private void swap(int[] nums, int i, int j) {
27+
int temp = nums[i];
28+
nums[i] = nums[j];
29+
nums[j] = temp;
2830
}
2931
}

0 commit comments

Comments
 (0)