You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/main/java/g0001_0100/s0031_next_permutation/readme.md
+62-1Lines changed: 62 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -37,4 +37,65 @@ The replacement must be **[in place](http://en.wikipedia.org/wiki/In-place_algor
37
37
**Constraints:**
38
38
39
39
*`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
+
publicclassSolution {
55
+
publicvoidnextPermutation(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
// Helper method to swap two elements in the array
93
+
privatevoidswap(int[] nums, inti, intj) {
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