【Next Permutation】cpp

题目

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

代码

class Solution {
public:
    void nextPermutation(vector<int> &num) {
        const int len = num.size();
        if (len<2) return;
        std::vector<int>::iterator pivot=num.end();
        // find the pivot pointer
        for (std::vector<int>::iterator i = num.end()-1; i != num.begin(); --i)
        {
            if ( *i>*(i-1) )
            {
                pivot = i-1;
                break;
            }
        }
        // if the largest, directly reverse
        if ( pivot==num.end() )
        {
            std::reverse(num.begin(), num.end());
            return;
        }
        // else exchange the value of pivot and it‘s next larger element
        std::vector<int>::iterator next_larger_pivot = pivot;
        for (std::vector<int>::iterator i = num.end()-1; i != num.begin(); --i)
        {
            if ( *pivot<*i )
            {
                next_larger_pivot = i;
                break;
            }
        }
        std::swap(*pivot, *next_larger_pivot);
        // reverse the pivot‘s right elements
        std::reverse(pivot+1, num.end());
    }
}

Tips:

上网搜搜Next Permutation的算法,分四步:

1. 从右往左 找左比右小的左 记为pivot

2. 从右往左 找第一个比pivot大的 记为next_larger_pivot

3. 交换pivot与next_larger_pivot所指向的元素

4. 让pivot右边的元素(不包括pivot)逆序

按照上面的算法,多测测case,找找边界条件。

注意找到pivot和next_larger_pivot之后要break退出循环。

时间: 2024-11-03 23:10:48

【Next Permutation】cpp的相关文章

【Word Break】cpp

题目: Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, givens = "leetcode",dict = ["leet", "code"]. Return true becau

【Sudoku Solver】cpp

题目: Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by the character '.'. You may assume that there will be only one unique solution. A sudoku puzzle... ...and its solution numbers marked in red. 代码: cla

【Subsets II】cpp

题目: Given a collection of integers that might contain duplicates, nums, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example,If nums = [1,2,2], a sol

【LRU Cache】cpp

题目: Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.

【Rotate List】cpp

题目: Given a list, rotate the list to the right by k places, where k is non-negative. For example:Given 1->2->3->4->5->NULL and k = 2,return 4->5->1->2->3->NULL. 代码: /** * Definition for singly-linked list. * struct ListNode {

【Text Justification】cpp

题目: Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pa

【Simplify Path】cpp

题目: Given an absolute path for a file (Unix-style), simplify it. For example,path = "/home/", => "/home"path = "/a/./b/../../c/", => "/c" click to show corner cases. Corner Cases: Did you consider the case whe

【Implement strStr() 】cpp

题目: Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Update (2014-11-02):The signature of the function had been updated to return the index instead of the pointer. If you st

【Valid Palindrome】cpp

题目: Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example,"A man, a plan, a canal: Panama" is a palindrome."race a car" is not a palindrome. Note:Have you consider tha