mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-07 01:44:56 +08:00
update solution 0031 & 0048
This commit is contained in:
@ -1,14 +1,43 @@
|
||||
// https://leetcode.com/problems/next-permutation/discuss/1554932/Go-Submission-with-Explanation
|
||||
// Time O(N) , Space: O(1)
|
||||
|
||||
package leetcode
|
||||
|
||||
// [2,(3),6,5,4,1] -> 2,(4),6,5,(3),1 -> 2,4, 1,3,5,6
|
||||
// 解法一
|
||||
func nextPermutation(nums []int) {
|
||||
i, j := 0, 0
|
||||
for i = len(nums) - 2; i >= 0; i-- {
|
||||
if nums[i] < nums[i+1] {
|
||||
break
|
||||
}
|
||||
}
|
||||
if i >= 0 {
|
||||
for j = len(nums) - 1; j > i; j-- {
|
||||
if nums[j] > nums[i] {
|
||||
break
|
||||
}
|
||||
}
|
||||
swap(&nums, i, j)
|
||||
}
|
||||
reverse(&nums, i+1, len(nums)-1)
|
||||
}
|
||||
|
||||
func reverse(nums *[]int, i, j int) {
|
||||
for i < j {
|
||||
swap(nums, i, j)
|
||||
i++
|
||||
j--
|
||||
}
|
||||
}
|
||||
|
||||
func swap(nums *[]int, i, j int) {
|
||||
(*nums)[i], (*nums)[j] = (*nums)[j], (*nums)[i]
|
||||
}
|
||||
|
||||
// 解法二
|
||||
// [2,(3),6,5,4,1] -> 2,(4),6,5,(3),1 -> 2,4, 1,3,5,6
|
||||
func nextPermutation1(nums []int) {
|
||||
var n = len(nums)
|
||||
var pIdx = checkPermutationPossibility(nums)
|
||||
if pIdx == -1 {
|
||||
reverse(nums, 0, n-1)
|
||||
reverse(&nums, 0, n-1)
|
||||
return
|
||||
}
|
||||
|
||||
@ -16,26 +45,14 @@ func nextPermutation(nums []int) {
|
||||
// start from right most to leftward,find the first number which is larger than PIVOT
|
||||
for rp > 0 {
|
||||
if nums[rp] > nums[pIdx] {
|
||||
swap(nums, pIdx, rp)
|
||||
swap(&nums, pIdx, rp)
|
||||
break
|
||||
} else {
|
||||
rp--
|
||||
}
|
||||
}
|
||||
// Finally, Reverse all elements which are right from pivot
|
||||
reverse(nums, pIdx+1, n-1)
|
||||
}
|
||||
|
||||
func swap(nums []int, i, j int) {
|
||||
nums[i], nums[j] = nums[j], nums[i]
|
||||
}
|
||||
|
||||
func reverse(nums []int, s int, e int) {
|
||||
for s < e {
|
||||
swap(nums, s, e)
|
||||
s++
|
||||
e--
|
||||
}
|
||||
reverse(&nums, pIdx+1, n-1)
|
||||
}
|
||||
|
||||
// checkPermutationPossibility returns 1st occurrence Index where
|
||||
|
@ -1,8 +1,24 @@
|
||||
// Time: O(N) Space: O(1)
|
||||
|
||||
package leetcode
|
||||
|
||||
// 解法一
|
||||
func rotate(matrix [][]int) {
|
||||
length := len(matrix)
|
||||
// rotate by diagonal 对角线变换
|
||||
for i := 0; i < length; i++ {
|
||||
for j := i + 1; j < length; j++ {
|
||||
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
|
||||
}
|
||||
}
|
||||
// rotate by vertical centerline 竖直轴对称翻转
|
||||
for i := 0; i < length; i++ {
|
||||
for j := 0; j < length/2; j++ {
|
||||
matrix[i][j], matrix[i][length-j-1] = matrix[i][length-j-1], matrix[i][j]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 解法二
|
||||
func rotate1(matrix [][]int) {
|
||||
n := len(matrix)
|
||||
if n == 1 {
|
||||
return
|
||||
|
Reference in New Issue
Block a user