# Ruby 在力扣做的一道题，相当之诡异

https://leetcode-cn.com/problems/next-permutation/

``````实现获取下一个排列的函数，算法需要将给定数字序列重新排列成字典序中下一个更大的排列。

1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

``````

``````# @param {Integer[]} nums
# @return {Void} Do not return anything, modify nums in-place instead.
def next_permutation(nums)
result = nums.sort.dup
(0..nums.length - 1).reverse_each do |i|
if nums[i - 1] && nums[i] > nums[i - 1]
ex_num = nums[i..-1].sort.find {|n| n > nums[i-1] }
ex_index = nums.index.with_index {|n, j| j > i - 1 && n == ex_num}
nums[i-1], nums[ex_index] = nums[ex_index], nums[i-1]
result = (nums[0..i-1] + nums[i..-1].sort).dup
break
end
end
result
end
``````

``````next_permutation([1,3,2])
``````

luikore 回复

``````# @param {Integer[]} nums
# @return {Void} Do not return anything, modify nums in-place instead.
def next_permutation(nums)
result = nums.sort.dup # 这里符合题目要求的额外常数空间吗？
(0..nums.length - 1).reverse_each do |i|
if nums[i - 1] && nums[i] > nums[i - 1]
ex_num = nums[i..-1].sort.find {|n| n > nums[i-1] }
ex_index = nums.index.with_index {|n, j| j > i - 1 && n == ex_num}
nums[i-1], nums[ex_index] = nums[ex_index], nums[i-1]
result = (nums[0..i-1] + nums[i..-1].sort).dup
break
end
end
result # 看注释，题目要求不返回值，只在 nums 上操作。为什么要返回 result 呢？
end
``````
IchiNiNiIchi 回复

lithium4010 回复

``````# @param {Integer[]} nums
# @return {Void} Do not return anything, modify nums in-place instead.
def next_permutation(nums)
need_sort = true
(0..nums.length - 1).reverse_each do |i|
if nums[i - 1] && nums[i] > nums[i - 1]
ex_num = nums[i..-1].sort.find {|n| n > nums[i-1] }
ex_index = nums.index.with_index {|n, j| j > i - 1 && n == ex_num}
nums[i-1], nums[ex_index] = nums[ex_index], nums[i-1]
nums[i..-1] = nums[i..-1].sort
need_sort = false
break
end
end
nums.sort! if need_sort
end
``````