Skip to content

Commit bf2a2a5

Browse files
authored
Update README with 'Next Permutation' solution
Added detailed explanation and implementation for the 'Next Permutation' problem in Java.
1 parent 2ca7d75 commit bf2a2a5

File tree

1 file changed

+62
-1
lines changed
  • src/main/java/g0001_0100/s0031_next_permutation

1 file changed

+62
-1
lines changed

src/main/java/g0001_0100/s0031_next_permutation/readme.md

Lines changed: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,4 +37,65 @@ The replacement must be **[in place](http://en.wikipedia.org/wiki/In-place_algor
3737
**Constraints:**
3838

3939
* `1 <= nums.length <= 100`
40-
* `0 <= nums[i] <= 100`
40+
* `0 <= nums[i] <= 100`
41+
42+
To solve the "Next Permutation" problem in Java with a `Solution` class, we can follow these steps:
43+
44+
1. Define a `Solution` class.
45+
2. Define a method named `nextPermutation` that takes an integer array `nums` as input and modifies it to find the next permutation in lexicographic order.
46+
3. Find the first index `i` from the right such that `nums[i] > nums[i - 1]`. If no such index exists, reverse the entire array, as it's already the last permutation.
47+
4. Find the smallest index `j` from the right such that `nums[j] > nums[i - 1]`.
48+
5. Swap `nums[i - 1]` with `nums[j]`.
49+
6. Reverse the suffix of the array starting from index `i`.
50+
51+
Here's the implementation:
52+
53+
```java
54+
public class Solution {
55+
public void nextPermutation(int[] nums) {
56+
int n = nums.length;
57+
58+
// Step 1: Find the first index i from the right such that nums[i] > nums[i - 1]
59+
int i = n - 1;
60+
while (i > 0 && nums[i] <= nums[i - 1]) {
61+
i--;
62+
}
63+
64+
// Step 2: If no such index exists, reverse the entire array
65+
if (i == 0) {
66+
reverse(nums, 0, n - 1);
67+
return;
68+
}
69+
70+
// Step 3: Find the smallest index j from the right such that nums[j] > nums[i - 1]
71+
int j = n - 1;
72+
while (nums[j] <= nums[i - 1]) {
73+
j--;
74+
}
75+
76+
// Step 4: Swap nums[i - 1] with nums[j]
77+
swap(nums, i - 1, j);
78+
79+
// Step 5: Reverse the suffix of the array starting from index i
80+
reverse(nums, i, n - 1);
81+
}
82+
83+
// Helper method to reverse a portion of the array
84+
private void reverse(int[] nums, int start, int end) {
85+
while (start < end) {
86+
swap(nums, start, end);
87+
start++;
88+
end--;
89+
}
90+
}
91+
92+
// Helper method to swap two elements in the array
93+
private void swap(int[] nums, int i, int j) {
94+
int temp = nums[i];
95+
nums[i] = nums[j];
96+
nums[j] = temp;
97+
}
98+
}
99+
```
100+
101+
This implementation provides a solution to the "Next Permutation" problem in Java. It finds the next lexicographically greater permutation of the given array `nums` and modifies it in place.

0 commit comments

Comments
 (0)