【leetcode】Next Permutation(middle)

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 4 2 5 7 6 3 中的 5 7, 这表示,7 6 3 是一个连续递减的序列,即这三个数字可以组成的最大的数。 把这三个数翻转,就是 3 6 7即这三个数字可以组成的最小的数字。把5与这三个数字中比它大的最小的数字与它交换变成 1 4 2 6 7 5 3,即下一个较大的数字。注意,像2 3 1 3 3 这样后面比交换点数大一点的数有相同的时候,后面翻转后,交换后面的那个。

class Solution {
public:
    void nextPermutation(vector<int> &num)
    {
        if (num.empty()) return;

        // in reverse order, find the first number which is in increasing trend (we call it violated number here)
        int i;
        for (i = num.size()-2; i >= 0; --i)
        {
            if (num[i] < num[i+1]) break;
        }

        // reverse all the numbers after violated number
        reverse(begin(num)+i+1, end(num));
        // if violated number not found, because we have reversed the whole array, then we are done!
        if (i == -1) return;
        // else binary search find the first number larger than the violated number
        auto itr = upper_bound(begin(num)+i+1, end(num), num[i]);
        // swap them, done!
        swap(num[i], *itr);
    }
};

我自己写得:思路是先交换,再翻转。比上面的繁琐一点。

void nextPermutation(vector<int> &num) {
        if(num.empty()) return;
        bool b = false;
        int chg1 = 0, chg2 = 0;
        int post = num.size() - 1;
        for(int i = num.size() - 2; i >= 0; --i)
        {
            if(num[post] > num[i])
            {
                b = true;
                chg1 = i;
                chg2 = post;
                break;
            }
            post = i;
        }

        if(!b)
        {
            reverse(num.begin(), num.end());
            return;
        }

        for(int i = chg1 + 1; i < num.size(); i++)
        {
            if(num[i] > num[chg1] && num[i] <= num[chg2])
                chg2 = i;
        }
        swap(num[chg1], num[chg2]);

        int l1 = chg1 + 1;
        int l2 = num.size() - 1;
        while(l1 < l2)
        {
            swap(num[l1++], num[l2--]);
        }
        return;
    }
时间: 2024-11-05 12:18:20

【leetcode】Next Permutation(middle)的相关文章

【leetcode】Reverse Integer(middle)☆

Reverse digits of an integer. Example1: x = 123, return 321Example2: x = -123, return -321 总结:处理整数溢出的方法 ①用数据类型转换long  或 long long ②在每次循环时先保存下数字变化之前的值,处理后单步恢复看是否相等 (比③好) ③整体恢复,看数字是否相等. 思路:注意30000这样以0结尾的数字,注意越界时返回0. 我检查越界是通过把翻转的数字再翻转回去,看是否相等. int rever

【leetcode】Reorder List (middle)

Given a singly linked list L: L0→L1→…→Ln-1→Ln,reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… You must do this in-place without altering the nodes' values. For example,Given {1,2,3,4}, reorder it to {1,4,2,3}. 思路: 先把链表分成两节,后半部分翻转,然后前后交叉连接. 大神的代码比我的简洁,注意分两节时用快

【leetcode】Word Break (middle)

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 because &

【leetcode】House Robber (middle)

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will autom

【leetcode】3Sum Closest(middle)

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. For example, given array S = {-1 2

【leetcode】Partition List(middle)

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions. For example,Given 1->4->3->2

【leetcode】Dungeon Game (middle)

The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his wa

【leetcode】Rotate Image(middle)

You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Follow up:Could you do this in-place? 思路:我的思路,先沿对角线对称,再左右对称. void rotate(int **matrix, int n) { //先沿对角线对称 for(int i = 0; i < n; i++) { for(int j = 0;

【leetcode】Spiral Matrix(middle)

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. For example,Given the following matrix: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] You should return [1,2,3,6,9,8,7,4,5]. 思路:就按照螺旋矩阵的规律 用n记录旋转圈数 每