当前位置:网站首页>数组 旋转数组

数组 旋转数组

2022-06-10 20:50:00 Morris_

LC 旋转数组

思路:将末尾的元素移动到首位,其他位置的元素向后移动一位,循环k次

  • Swift
    /* 例: nums = [1,2,3], k = 4 [3,1,2] [2,3,1] [1,2,3] [3,1,2] 每次将最后以为元素移动到首位,其他位元素依次向后移动一位;循环移动k次 */
    
    func rotate(_ nums: inout [Int], _ k: Int) {
    
        
        var k: Int = k
        
        while k > 0 {
    
            
            let temp: Int = nums.last!
            
            var index = nums.count - 1
            while index > 0 {
    
                
                nums[index] = nums[index - 1]
                
                index -= 1
            }
            
            nums[0] = temp
            
            k -= 1
        }
    }
原网站

版权声明
本文为[Morris_]所创,转载请带上原文链接,感谢
https://blog.csdn.net/Morris_/article/details/125197844