码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode 52] Next Permutation Report

时间:2015-06-08 06:12:20      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

Question:

Given a list of integers, which denote a permutation.

Find the next permutation in ascending order.

 
Example

For [1,3,2,3], the next permutation is [1,3,3,2]

For [4,3,2,1], the next permutation is [1,2,3,4]

Note

The list may contains duplicate integers.

What is Next Permutation?

The permutation with current charactors that is lexicographically next.

1234 -> 1243
4321 -> 1234
1243 -> 1324
2134 -> 2143

 

Idea:

技术分享

 

Answer:

 

 class Solution {
 public:
     /**
      * @param nums: An array of integers
      * @return: An array of integers that‘s next permuation
      */
     vector<int> nextPermutation(vector<int> &nums) {
         // write your code here
         if (nums.size() <= 1) {
             return nums;
         }
         
         //find first element that is smaller that next element
         int first_small_index = -1;
         for (int i = nums.size() - 2; i >= 0; --i) {
             if (nums[i] < nums[i+1]) {
                 first_small_index = i;
                 break;
             }
         }
         //find the first element that is just bigger than the element we found
         if (first_small_index != -1) {
             int first_bigger_index = first_small_index;
             for (int i = first_small_index + 1; i < nums.size(); ++i) {
                 if (nums[i] > nums[first_small_index]) {
                     first_bigger_index = i;
                 } else {
                     break;
                 }
             }
             swap(nums[first_small_index], nums[first_bigger_index]);
         }
         // Reverse rest array
         reverse(nums.begin() + first_small_index + 1, nums.end());
         
         return nums;
     }
 };

 

 

 

[leetcode 52] Next Permutation Report

标签:

原文地址:http://www.cnblogs.com/laoyu2012/p/4560028.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!