e*******s 发帖数: 1979 | 1 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
用例 1, 1, 5
在Leetcode上面出runtime error 在自己的machine上能出结果
简单的查了一下 error出在倒数第九行
swap(num[swp_index], num[index -1]);
自己写swap也是出错, 而且是错在index-1处
简单调试了下swp_index = 2, index - 1 = 1
都不存在Out of Bound
全代码如下
class Solution {
public:
void nextPermutation(vector &num) {
int len = num.size();
if(0 == len)
return;
else if(1 == len)
return;
else if(2 == len){
swap(num[0], num[1]);
return;
}
else
{
int index = len -1;
while(0 != index && num[index - 1] >= num[index])
{
--index;
}
int swp_index = index;
for(int i = index+1; i != len; ++i)
{
if(num[i] > num[index-1])
swp_index = i;
}
swap(num[swp_index], num[index -1]);
sort(num.begin()+index, num.end());
return;
}
return;
}
}; | e*******s 发帖数: 1979 | 2 解决了
Leetcode的用例报错似乎有点问题
事实上出错的并不是这个用例 而是3,2,1这个用例
【在 e*******s 的大作中提到】 : 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
|
|