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

    题意:找到下一个排列数

    思路:主要就是根据经验,要记住这个找排列数的规律

    (1) 首先从后往前找到第一个下降的位置,记为i,如果没有则证明是最后一个排序,下一个为原串的逆序

    (2) 从i往后,找到比i对应的数值大的当中最小的对应的index(由于后面都是降序的,所以找到第一个小于等于i对应的数值的前一个即为所求),如果没有则为length-1;

    注: (例如 2,3,6,5,4,1  第一个降序的为3 比3大的当中 最小的为4)

    (3) 交换nums[i] 和 nums[index] 

    (4) 将i后面的逆序

    代码:

    public class Solution {
        public void nextPermutation(int[] nums) {
            if(nums.length < 2)
                return;
            for(int i = nums.length - 2 ; i >= 0 ; i--) {
                if(nums[i] < nums[i+1]) {
                   int index = nums.length - 1;
                   for(int j = i + 1 ; j < nums.length ; j++) { // 找到比nums[index]大的当中最小的
                       if(nums[j] <= nums[i]){  //一定要有等号哦
                           index = j - 1;
                           break;
                       }
                   }
                   int temp = nums[i];
                   nums[i] = nums[index];
                   nums[index] = temp;
                   
                   reverse(nums, i+1, nums.length-1);
                   return;
                }
            }
            
            reverse(nums, 0, nums.length-1);
            return;
        }
        
        public void reverse(int[] nums, int begin, int end) {
            if(begin == end)
                return;
            
            while(begin < end) {
                int temp = nums[begin];
                nums[begin] = nums[end];
                nums[end] = temp;
                begin++;
                end--;
            }
        } 
    }
  • 相关阅读:
    Agile PLM bom表结构学习笔记
    火狐书签同步服务无法同步问题解决
    EasyExcel使用笔记
    给EasyUI查询按钮添加回车事件.
    让bat异常之后不直接关闭窗口的办法.
    DROP TABLE、TRUNCATE TABLE和DELETE的区别
    DUMPBIN工具的使用
    Java Build Path 详解
    用eclipse中打开已存在的Java Project
    .net core、微服务 开源项目
  • 原文地址:https://www.cnblogs.com/TinyBobo/p/4699549.html
Copyright © 2011-2022 走看看