24
loading...
This website collects cookies to deliver better user experience
Input: nums = [1,2,3]
Output: [1,3,2]
Input: nums = [3,2,1]
Output: [1,2,3]
Input: nums = [1,1,5]
Output: [1,5,1]
Input: nums = [1]
Output: [1]
1 <= nums.length <= 100
0 <= nums[i] <= 100
O (n x n!)
- WHAT!
input = [1, 2, 3]
solution = [1, 3, 2]
input = [1, 3, 2]
solution = [2, 1, 3]
[1, 3, 2]
we reached till i = 0 (1)
-1
-> we cannot produce a bigger number, thanks to the problem statement, we simply reverse the number and return.i >=0
, we again start from the end (say j
), until we find a number greater than i
j = 2 (2)
[2, 3, 1]
2 [3, 1] -> 2 [1, 3]
public static void nextPermutation(int[] nums) {
int i = nums.length - 2;
while (i >= 0 && nums[i + 1] <= nums[i]) {
i--;
}
if (i >= 0) {
while (nums[j] <= nums[i]) {
j--;
}
swap(nums, i, j);
}
reverse(nums, i + 1);
}
private static void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
private static void reverse(int[] nums, int start) {
int i = start, j = nums.length - 1;
while (i < j) {
swap(nums, i, j);
i++;
j--;
}
}
python
-> Enjoy ;)def next_perm(n):
i = len(n) - 2
while i >= 0 and n[i + 1] <= n[i]:
i -= 1
if i >= 0:
j = len(n) - 1
while n[j] <= n[i]:
j -= 1
swap(n, i, j)
return reverse(n, i + 1)
def swap(n, i, j):
n[i], n[j] = n[j], n[i]
def reverse(n, from_index):
res = []
for i in range(0, from_index):
res.append(n[i])
for i in range(len(n) - 1, from_index - 1, -1):
res.append(n[i])
return res