当前位置:网站首页>Array rotates the array from bits of the specified length

Array rotates the array from bits of the specified length

2022-06-10 22:11:00 Morris_

Rotated array

 Input : nums = [1,2,3,4,5,6,7], k = 3 
 Output : [5,6,7,1,2,3,4]

Bits from the specified length , Rotated array

Swift

var newArray: [Int] = []
let array: [Int] = [10, 20, 30, 40, 50, 60]
let k: Int = 3
for i in 0..<array.count {
    
    let j: Int = (i + k) % array.count
    print(j, array[j])
    newArray.append(array[j])
}
print(array)
print(newArray)

Output is as follows :

3 40
4 50
5 60
0 10
1 20
2 30
[10, 20, 30, 40, 50, 60]
[40, 50, 60, 10, 20, 30]

newArray Is the rotated array

take array Replace all elements

var newArray: [Int] = []
var array: [Int] = [10, 20, 30, 40, 50, 60]
let k: Int = 3
for i in 0..<array.count {
    
    let j: Int = (i + k) % array.count
    print(j, array[j])
    newArray.append(array[j])
}
array.replaceSubrange(0..<array.count, with: newArray)
print(array)

Optimize the implementation of the last interview , Take an intermediate array temp

var array: [Int] = [10, 20, 30, 40, 50, 60]
let temp: [Int] = array
let k: Int = 3
for i in 0..<array.count {
    
    let j: Int = (i + k) % array.count
    let ele = temp[j]
    print(j, ele)
    array.replaceSubrange(i..<i+1, with: [ele])
}
print(array)

The function is implemented as follows

func rotate(_ nums: inout [Int], _ k: Int) {
    
    if k > 0 && k < nums.count {
    
        let temp = nums
        for i in 0..<nums.count {
    
            nums.replaceSubrange(i..<i+1, with: [temp[(i+k) % nums.count]])
        }
    }
}

call

var nums: [Int] = [1,2,3,4,5,6,7,8]
let k: Int = 3
rotate(&nums, k)
print(nums)

Output

[4, 5, 6, 7, 8, 1, 2, 3]
原网站

版权声明
本文为[Morris_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206102049515908.html