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

    Runtime: 12ms. 

     1 class Solution {
     2 public:
     3     void nextPermutation(vector<int>& nums) {
     4         if(nums.empty()) return;
     5 
     6         int n = nums.size();
     7         
     8         // find the first decreasing number from right to left
     9         int firstDecreaseIndex = n - 1;
    10         for(int i = n - 2; i >= 0; i--) {
    11             if(nums[i] < nums[i + 1]) {
    12                 firstDecreaseIndex = i;
    13                 break;
    14             }
    15         }
    16         
    17         if(firstDecreaseIndex == n - 1) {
    18             reverse(nums.begin(), nums.end());
    19             return;
    20         }
    21         
    22         // find the first number which is larger than nums[firstDecreaseIndex]
    23         int firstLargerIndex;
    24         for(int i = n - 1; i >= 0; i--) {
    25             if(nums[i] > nums[firstDecreaseIndex]) {
    26                 firstLargerIndex = i;
    27                 break;
    28             }
    29         }
    30         
    31         swap(nums[firstDecreaseIndex], nums[firstLargerIndex]);
    32         
    33         // reverse numbers between firstDecreaseIndex + 1 and n - 1
    34         for(int i = firstDecreaseIndex + 1, j = n - 1; i < j; i++, j--) {
    35             swap(nums[i], nums[j]);
    36         }
    37     }
    38 };
  • 相关阅读:
    条件编译中的基本语法
    UITableView中headerView视察滚动的简单实现
    CocoaPods使用简单回顾
    CocoaPods第三方类库管理工具的简单使用
    Xcode中release和debug模式
    转:关于LazyTableImage
    汉字与UTF-8编码之间的转换
    结构体与字符串之间的转换
    MFC中小笔记(二)
    升级 WIN8.1 VC6.0和 Visual Assist 的使用问题
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/5755106.html
Copyright © 2011-2022 走看看