zoukankan      html  css  js  c++  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,3 → 1,3,2
    3,2,1 → 1,2,3
    1,1,5 → 1,5,1

    题意:用现有的数字排序,找出比现在数字大的最小的数,如果没有的话,重新排序为最小值

    思路:从低位往高位遍历,如果相邻高位比现位置值大的话,break

     1 class Solution(object):
     2     def nextPermutation(self, nums):
     3         """
     4         :type nums: List[int]
     5         :rtype: void Do not return anything, modify nums in-place instead.
     6         """
     7         flag = 0
     8         l = len(nums)
     9         for i in range(l-1,0,-1):
    10             if nums[i-1]<nums[i]:
    11                 flag = 1
    12                 break
    13         if 1 == flag:
    14             tmp = nums[i:]
    15             tmp.sort()
    16             nums[i:]=tmp
    17             for k in range(i,l):
    18                 if nums[k]>nums[i-1]:
    19                     tmp = nums[k]
    20                     nums[k] = nums[i-1]
    21                     nums[i-1] = tmp
    22                     break
    23         else:
    24             nums.reverse()
  • 相关阅读:
    poj 1061 (扩展欧几里德算法)
    字符串 (扫一遍 + 计数)
    快排 + 二分
    勾股定理
    WD
    Acmer--弱水三千,只取一瓢
    朱光潜给青年的十二封信 之 谈升学和选课
    朱光潜给青年的十二封信 之 谈读书
    小白书--求 n!
    N阶行列式---常见的几种运算
  • 原文地址:https://www.cnblogs.com/fcyworld/p/6285077.html
Copyright © 2011-2022 走看看