由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - LeetCode Runtime Error 一问
相关主题
请教一道Leetcode 题一个容易记忆的permutation算法
Given a string, find all its permutations without any repetition?LeetCode RunTime Error一问
permuation sequence 超时Non-recursive permutation
如何避免permutation中的重复计数Leetcode Recover Binary Search Tree一问
Exposed上一道string permutation的题实现next_permutation
最近面试的一个问题调试成功的next_permutation代码
如何写内存速度最优化的string permutation?有重复字符请教 permute vector of vectors 如何实现,谢谢大家
leetcode: largest rectangle in histogram求帮助今天才整明白Permutation的最优解!?
相关话题的讨论汇总
话题: index话题: num话题: swp话题: len话题: leetcode
进入JobHunting版参与讨论
1 (共1页)
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

1 (共1页)
进入JobHunting版参与讨论
相关主题
今天才整明白Permutation的最优解!?Exposed上一道string permutation的题
String permunation question (CS)最近面试的一个问题
Permutation leetcode-如何写内存速度最优化的string permutation?有重复字符
问题:Find the minimum number of "swaps" needed to sort an arrayleetcode: largest rectangle in histogram求帮助
请教一道Leetcode 题一个容易记忆的permutation算法
Given a string, find all its permutations without any repetition?LeetCode RunTime Error一问
permuation sequence 超时Non-recursive permutation
如何避免permutation中的重复计数Leetcode Recover Binary Search Tree一问
相关话题的讨论汇总
话题: index话题: num话题: swp话题: len话题: leetcode