zoukankan      html  css  js  c++  java
  • [Leetcode 67] 31 Next Permutation

    Problem:

    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

    Analysis:

    First we need to find the first pair that A_i-1 < A_i, and then find the minimum element that is great than A_i-1 from A_i to A_end

    swap A_i-1 and A_min_max.

    at last, sort all the elements of A_i to A_end.

    Then we can get the answer.

    Code:

     1 class Solution {
     2 public:
     3     void nextPermutation(vector<int> &num) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         int i, min_max;
     7         for (i=min_max=num.size()-1; i>0; i--) {
     8             if (num[i] > num[min_max])
     9                 min_max = i;
    10             
    11             if (num[i] > num[i-1])
    12                 break;
    13         }
    14         
    15         if (i == 0)
    16             reverse(num.begin(), num.end());
    17         else {
    18             for (int j=i; j<num.size(); j++) {
    19                 if (num[j] > num[i-1] && num[j] <= num[min_max])
    20                     min_max = j;
    21             }
    22             
    23             swap(num[i-1], num[min_max]);
    24             
    25             sort(num.begin()+i, num.end());
    26         }
    27     }
    28     
    29     void swap(int &a, int &b) {
    30         int tmp = a;
    31         a = b;
    32         b = tmp;
    33     }
    34 };
    View Code
  • 相关阅读:
    希尔排序算法
    直接插入排序和折半插入排序算法
    快排序算法
    部分博文目录索引(C语言+算法)
    Gnome排序算法
    选择排序算法
    pip运行报错Fatal error in launcher: Unable to create process using pip.exe
    Java Selenium封装--RemoteWebDriver
    Java Selenium封装--RemoteWebElement
    selenium webdriver自动化对日期控件的处理
  • 原文地址:https://www.cnblogs.com/freeneng/p/3192910.html
Copyright © 2011-2022 走看看