Leetcode 题目解析之 Next Permutation
【摘要】 Leetcode 题目解析之 Next Permutation
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
public void nextPermutation(int[] nums) {
if (nums == null || nums.length < 2) {
return;
}
int p = 0;
for (int i = nums.length - 2; i >= 0; i--) {
if (nums[i] < nums[i + 1]) {
p = i;
break;
}
}
int q = 0;
for (int i = nums.length - 1; i > p; i--) {
if (nums[i] > nums[p]) {
q = i;
break;
}
}
if (p == 0 && q == 0) {
reverse(nums, 0, nums.length - 1);
return;
}
int temp = nums[p];
nums[p] = nums[q];
nums[q] = temp;
if (p < nums.length - 1) {
reverse(nums, p + 1, nums.length - 1);
}
}
private void reverse(int[] nums, int left, int right) {
while (left < right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
}
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)