在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given an array, rotate the array to the right by k steps, where k is non-negative. Example 1: Input: Example 2: Input:
Note:
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: 示例 2: 输入:
说明:
48ms 1 class Solution { 2 func rotate(_ nums: inout [Int], _ k: Int) { 3 guard nums.count > 1 else { 4 return 5 } 6 7 guard k > 0 else { 8 return 9 } 10 11 let k = k % nums.count 12 nums = Array(nums[(nums.count - k)..<nums.count]) + Array(nums[0..<(nums.count - k)]) 13 } 14 } 48ms 1 class Solution { 2 func rotate(_ nums: inout [Int], _ k: Int) { 3 let n = nums.count 4 let numRoations = k % n 5 var rotated = [Int]() 6 for i in n-numRoations..<n { 7 rotated.append(nums[i]) 8 } 9 for j in 0..<n-numRoations { 10 rotated.append(nums[j]) 11 } 12 nums = rotated 13 } 14 } 52ms 1 class Solution { 2 func rotate(_ nums: inout [Int], _ k: Int) { 3 rotate1(&nums, k) 4 } 5 6 func rotate1(_ nums: inout [Int], _ k: Int) { 7 var r: [Int] = Array(repeating: 0, count: nums.count) 8 var kk = nums.count - (k % nums.count) 9 for i in 0..<nums.count { 10 r[i] = nums[(i + kk) % nums.count] 11 } 12 for (i, num) in r.enumerated() { 13 nums[i] = num 14 } 15 } 16 } 56ms 1 class Solution { 2 func rotate(_ nums: inout [Int], _ k: Int) { 3 guard nums.count > 0, k > 0 else { 4 return 5 } 6 7 let k = k%nums.count 8 9 rotate(&nums, 0, nums.count-k-1) 10 rotate(&nums, nums.count-k, nums.count-1) 11 rotate(&nums, 0, nums.count-1) 12 } 13 14 private func rotate(_ nums: inout [Int], _ left: Int, _ right: Int) { 15 if left == right || nums.count == 0 { return } 16 17 var i = left, j = right 18 19 while i < j { 20 let temp = nums[i] 21 nums[i] = nums[j] 22 nums[j] = temp 23 i += 1 24 j -= 1 25 } 26 } 27 } 64ms 1 class Solution { 2 func rotate(_ nums: inout [Int], _ k: Int) { 3 var n = nums.count 4 let ind = n-1-k%n 5 nums += nums[0...ind] 6 nums.removeSubrange(0...ind) 7 } 8 }
|
请发表评论