Skip to content

Commit

Permalink
[LeetCode] Add January 31.
Browse files Browse the repository at this point in the history
  • Loading branch information
pin3da authored Jan 31, 2021
1 parent 9e1aced commit b4426a4
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions solved/LeetCode/Challenges/2020/January/31.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
class Solution {
fun nextPermutation(nums: IntArray): Unit {
if (nums.size <= 1) {
return
}
var last = nums.size - 2
while (last >= 0) {
if (nums[last + 1] > nums[last]) {
var right = last + 1
for (i in last + 1 until nums.size) {
if (nums[i] > nums[last]) {
right = i
}
}
nums[right] = nums[last]. also {
nums[last] = nums[right]
}
break
}
last--
}
println(last)
nums.reverse(last + 1, nums.size)
}
}


fun IntArray.reverse(fromIndex: Int, toIndex: Int) {
var left = fromIndex
var right = toIndex -1
while (left < right) {
this[left] = this[right].also {
this[right] = this[left]
}
left++
right--
}
}

0 comments on commit b4426a4

Please sign in to comment.