注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
本帖最后由 mmxmw 于 2019-8-2 09:03 编辑
以下是小弟的solution:
# 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 and use only constant 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
class Solution:
def nextPermutation(self, nums) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
if len(nums) <= 1:
return nums
for i in list(range(len(nums)-1, 0, -1)):
if nums <= nums[i-1]:
pass
else:
k = self.switch_pos(i-1, len(nums)-1, nums)
nums[i-1], nums[k] = nums[k], nums[i-1]
a = nums[i:]
a.sort()
return nums[:i] + a
nums.sort()
return nums
def switch_pos(self, start, end, nums):
curr = end
while curr >= start:
if nums[curr] > nums[start]:
return curr
else:
curr -= 1
if __name__ == '__main__':
x = Solution()
nums = [1, 3, 2]
print(x.nextPermutation(nums))
Test case: nums = [1, 3, 2]
在本地output是[3, 1, 2],正确。但Leetcode提交后显示
Your input
[1, 3, 2]
Output
[2,3,1]
Expected
[2,1,3]
请问是咋回事?
|