当前位置:网站首页>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]
边栏推荐
- Can I make up the exam if I fail the soft exam? Here comes the answer
- Qingniao Changping campus of Peking University: can I learn UI with a high school degree?
- 数组 移动0
- Kdd2022 | neural network compression of depth map based on antagonistic knowledge distillation
- Constructing the implementation strategy of steam education for children
- 数组 删除数组中的重复项
- Are you still writing the TS type code
- 【MySQL】錶數據的增删查改(DML)
- C语言qsort()函数的使用(详解)
- Self made table
猜你喜欢
随机推荐
【Microsoft Azure 的1024种玩法】七十五.云端数据库迁移之快速将阿里云RDS SQL Server无缝迁移到Azure SQL Databas
Kdd2022 | neural network compression of depth map based on antagonistic knowledge distillation
SQL第四练:字符串处理函数
Icml2022 | sharp maml: model independent meta learning for sharpness perception
Mysql的回表查询?如何避免?
C language ---9 first knowledge of macros and pointers
数组 只出现一次的数字
[NK] question de calcul de 51 g pour le match lunaire Bullock
【MySQL】表的约束
CCF class a conference or journal - regression related papers
NFT版权/版税
MySQL inserts query results into other tables
SQL Server row to column (pivot), column to row (unpivot)
[nk] Niuke monthly race 51g calculation problem
SQL Server2019安装的详细步骤实战记录(亲测可用)
C language learning review -- 1 basic knowledge review
sql server行转列(pivot),列转行(unpivot)
磁盘序列号,磁盘ID,卷序列号的区别
Abbexa acrylamide peg NHS instructions
数组 旋转数组







