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());
}
};
相關文章
- Leetcode-Next PermutationLeetCode
- Next Permutation leetcode javaLeetCodeJava
- [LeetCode] Next Permutation 下一個排列LeetCode
- next_permutation函式函式
- Permutation Sequence leetcode javaLeetCodeJava
- [LeetCode]60. Permutation SequenceLeetCode
- LeetCode-Palindrome Permutation IILeetCode
- 全排列函式next_permutation在STL的使用函式
- Girl Permutation
- [LeetCode] 681. Next Closest TimeLeetCode
- 【leetcode】60. Permutation Sequence 全排列的第k位序的排列形式LeetCode
- 力扣(LeetCode)310力扣LeetCode
- Leetcode 231 Power of TwoLeetCode
- 【Leetcode】題目集:31-40LeetCode
- leetcode 231 2的冪LeetCode
- LeetCode31.下一個排列LeetCode
- Leetcode 231. Power of TwoLeetCode
- Leetcode Populating Next Right Pointers in Each NodeLeetCode
- [LintCode] Permutation in String
- Codeforces 452F Permutation
- LeetCode-131-分割回文串LeetCode
- LeetCode 第 231 題 (Power of Two)LeetCode
- LeetCode131:Palindrome PartitioningLeetCode
- Leetcode Populating Next Right Pointers in Each Node IILeetCode
- Populating Next Right Pointers in Each Node leetcode javaLeetCodeJava
- 使用 Fedora 31 和 Nextcloud 伺服器構建自己的雲Cloud伺服器
- [Leetcode學習-c++&java]Next Greater Element I ~ IIILeetCodeC++Java
- Populating Next Right Pointers in Each Node II leetcode javaLeetCodeJava
- LeetCode 31. 下一個排列 | PythonLeetCodePython
- [Leetcode]931.下降路徑最小和LeetCode
- [Leetcode]316.去除重複字母LeetCode
- 聊聊CBO的連線排列(Join Permutation)
- [CareerCup] 1.3 Permutation String 字串的排列字串
- [CF1718D] Permutation for Burenka 瞎扯
- row_vector and col_vector的建立 (Leetcode 807, Leetcode 531)LeetCode
- LeetCode演算法題-Next Greater Element I(Java實現)LeetCode演算法Java
- Leetcode-Populating Next Right Pointer in Binary Tree IILeetCode
- LeetCode 312 Burst Balloons 思路分析總結LeetCode