zoukankan      html  css  js  c++  java
  • 19.2.1 [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

    题意

    解出数组的下一个排列(字典序)

    (next_permutation)

    题解

     1 class Solution {
     2 public:
     3     void nextPermutation(vector<int>& nums) {
     4         int size = nums.size(), max = nums[size - 1], i;
     5         for (i = size - 2; i >= 0; i--) {
     6             if (nums[i] < max)
     7                 break;
     8             else
     9                 max = nums[i];
    10         }
    11         if (i == -1) {
    12             sort(nums.begin(), nums.end());
    13             return;
    14         }
    15         int j;
    16         for (j = i + 1; j < size; j++)
    17             if (nums[j] <= nums[i])
    18                 break;
    19         int tmp = nums[i];
    20         nums[i] = nums[j - 1];
    21         nums[j - 1] = tmp;
    22         auto p = nums.begin();
    23         while (i--)p++;
    24         sort(p+1, nums.end());
    25     }
    26 };
    View Code
  • 相关阅读:
    Reverse Integer
    First Bad Version
    Heaters
    Number of Segments in a String
    RPI学习--环境搭建_串口连接
    关键字const
    main函数参数的使用
    Redis 简单使用 and 连接池(python)
    南宁AI项目
    Go part 1 初探
  • 原文地址:https://www.cnblogs.com/yalphait/p/10345631.html
Copyright © 2011-2022 走看看