ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

LeetCode 0031 Next Permutation

2022-03-20 22:04:22  阅读:230  来源: 互联网

标签:nums 交换 大数 0031 尽可能 Permutation 升序 LeetCode 小数


原题传送门

1. 题目描述

2. Solution 1

1、思路分析
算法推导:

  1) 希望下一个数比当前数大。需要把后面的"大数"与前面的"小数"交换,就能得到一个更大的数。
     如: 123456,将 5和6 交换就能得到一个更大的数。
  2) 希望下一个数增加的幅度尽可能的小。
     2.1) 在尽可能靠右低位进行交换,需要从后往前查找。
     2.2) 将一个尽可能小的大数与前面的小数交换。
     2.3) 将大数换到前面后,需要将大数后面的所有数重置为升序,升序排列就是最小的排列。

2、代码实现

package Q0099.Q0031NextPermutation;

/*
  According to Wikipedia, a man named Narayana Pandita presented the following simple algorithm
  to solve this problem in the 14th century.

   1> Find the largest index k such that nums[k] < nums[k + 1]. If no such index exists, just reverse nums and done.
   2> Find the largest index l > k such that nums[k] < nums[l].
   3> Swap nums[k] and nums[l].
   4> Reverse the sub-array nums[k + 1:].

   The above algorithm can also handle duplicates and thus can be further
   used to solve Permutations and Permutations II.
   Time: O(n), Space: O(1)

   算法推导:
   1) 希望下一个数比当前数大。需要把后面的"大数"与前面的"小数"交换,就能得到一个更大的数。
      如: 123456,将 5和6 交换就能得到一个更大的数。
   2) 希望下一个数增加的幅度尽可能的小。
       2.1) 在尽可能靠右低位进行交换,需要从后往前查找。
       2.2) 将一个尽可能小的大数与前面的小数交换。
       2.3) 将大数换到前面后,需要将大数后面的所有数重置为升序,升序排列就是最小的排列。

 */
public class Solution {
    public void nextPermutation(int[] nums) {
        // corner case
        if (nums == null || nums.length == 0) return;
        int n = nums.length, k = n - 2, l = n - 1;
        while (k >= 0 && nums[k] >= nums[k + 1]) k--;  // Find 1st id k that breaks descending order
        if (k >= 0) {                                  // If not entirely descending
            while (nums[l] <= nums[k]) l--;            // Find rightmost first larger id l
            swap(nums, k, l);                          // swap k and l
        }
        reverse(nums, k + 1, n - 1);
    }

    public void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    public void reverse(int[] nums, int start, int end) {
        for (int i = start, j = end; i < j; i++, j--) swap(nums, i, j);
    }
}

标签:nums,交换,大数,0031,尽可能,Permutation,升序,LeetCode,小数
来源: https://www.cnblogs.com/junstat/p/16032303.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有