将一个数组平分为对应的子数组
需求:
将一个数组
let list = [1, 2, 3, 4, 5, 6, 7 , 8 ,9, 10, 11]
按照2个一组的子数组的形式返回,如有多余的,则自己为一个子数组。
let targetList = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11]]
实现算法 时间复杂度:O(n)
//分割数组
func dealListToTwoSubList<T>(list: [T]) -> [[T]] {
let count = list.count/2
let hasSingleValue = list.count%2 == 1
var targetList: [[T]] = []
for i in 0..<count {
let firstIndex = i * 2
let subList = Array(list[firstIndex...firstIndex+1])
targetList.append(subList)
}
//有余数, 加上最后一个
if hasSingleValue {
if let lastItem = list.last {
var subList: [T] = []
subList.append(lastItem)
targetList.append(subList)
}
}
print("\(targetList)")
return targetList
}