Leetcode 31 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 and use only constant 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
這個題的意思是找到下一個最大的排列數,方法類似於雙指標,從後往前掃,當遇到可以進行更換的數的時候進行更換,並使用reverse進行反轉後面的數,使得後面的數為最小的。
1)
class Solution {
public:
void nextPermutation(vector<int>& nums) {
if(nums.size() <= 1){
return ;
}
int i = nums.size() - 1;
while(i > 0 && nums[i] <= nums[i - 1]){
--i;
}
if(i == 0){
reverse(nums.begin(),nums.end());
}else{
int j = nums.size() - 1;
while(nums[j] <= nums[i - 1]){
--j;
}
swap(nums[j],nums[i - 1]);
reverse(nums.begin() + i , nums.end());
}
}
};
2)
static const auto _______ = [](){//大概是一種特殊的讀取數的形式
std::cout.sync_with_stdio(false);
cin.tie(0);
return 0;
}();
class Solution {
public:
void nextPermutation(vector<int>& a) {
int n=a.size();
int i;
for(i=n-1;i>0;i--) {
if(a[i]>a[i-1]) {
int k=i;
for(int j=i;j<n;j++) {
if(a[j]>a[i-1]&&a[j]<a[k])
k=j;
}
swap(a[i-1],a[k]);
break;
}
}
sort(a.begin()+i,a.end());
}
};
相關文章
- next_permutation
- next_permutation函式函式
- [LeetCode]60. Permutation SequenceLeetCode
- [LeetCode] 681. Next Closest TimeLeetCode
- LeetCode31.下一個排列LeetCode
- 2020/10/31·Leetcode·兩數之和LeetCode
- 【Leetcode】題目集:31-40LeetCode
- Girl Permutation
- LeetCode 31. 下一個排列 | PythonLeetCodePython
- 【leetcode】60. Permutation Sequence 全排列的第k位序的排列形式LeetCode
- [LintCode] Permutation in String
- G - Ban Permutation
- Leetcode 117. Populating Next Right Pointers in Each Node IILeetCode
- C. Game on PermutationGAM
- Yet Another Permutation ConstructiveStruct
- [Leetcode學習-c++&java]Next Greater Element I ~ IIILeetCodeC++Java
- 09/05 ? LeetCode 熱題 HOT 100 -- 22, 23,31LeetCode
- Codeforces 452F Permutation
- LeetCode演算法題-Next Greater Element I(Java實現)LeetCode演算法Java
- Codeforces_943_D_Permutation GameGAM
- [ARC176D] Swap Permutation
- CF1946E Girl Permutation
- 精讀《Permutation, Flatten, Absolute...》
- [CF1718D] Permutation for Burenka 瞎扯
- codeforces 1284C New Year and Permutation
- AtCoder Beginner Contest 282 G - Similar PermutationMILA
- 直播預告|1月31日,專家講解BIG-IP Next背後的故事
- hdu 6446 Tree and Permutation(dfs+思維)
- Solution - Atcoder ARC114F Permutation Division
- solution-2022 CCPC Guilin J. Permutation PuzzleGUI
- 31
- eslint-disable-next-line to ignore the next lineEsLint
- 日常 31
- hexo Next 配置Hexo
- next-route
- vue31Vue
- 實驗31
- 2024/5/31