zoukankan      html  css  js  c++  java
  • Java [leetcode 31]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,31,3,2
    3,2,11,2,3
    1,1,51,5,1

    解题思路:

    从整个数组的最后开始往前判断,直到找到相邻两个数是增加的,记录下这个位置为i;

    如果i小于0,表示整个数组的顺序是递减的;

    从数组的最后开始寻找,找到第一个大于nums[i]的数的位置,记为j;

    交换nums[i]和nums[j]的位置,然后对i后的所有数组进行倒序排列。

    注意边界问题,数组不要越界。

    代码如下:

    public class Solution {
        public void nextPermutation(int[] nums) {
    		if (nums.length < 2)
    			return;
    		int i, j, temp;
    		for (i = nums.length - 2; i >= 0; i--) {
    			if (nums[i] < nums[i + 1])
    				break;
    		}
    		for (j = nums.length - 1; j >= 0; j--) {
    			if (i < 0)
    				break;
    			if (nums[j] > nums[i])
    				break;
    		}
    		if (i >= 0) {
    			temp = nums[i];
    			nums[i] = nums[j];
    			nums[j] = temp;
    		}
    
    		if (i < nums.length - 2) {
    			for (int k = i + 1; k <= (nums.length - i - 2) / 2 + i + 1; k++) {
    				temp = nums[k];
    				nums[k] = nums[nums.length + i - k];
    				nums[nums.length + i - k] = temp;
    			}
    		}
    	}
    }
    
  • 相关阅读:
    spark发现新词
    树的算法总结
    机器学习树的算法总结
    Spark Streaming实例
    ubuntu上通用解压方式
    论MYSQL数据库数据错误的处理
    macOS Sierra上Opencv的安装与使用
    phpstudy2016 redis扩展 windows
    细说PHP7
    正则表达式与.htaccess的配置
  • 原文地址:https://www.cnblogs.com/zihaowang/p/4930287.html
Copyright © 2011-2022 走看看