將一個(gè)數(shù)組平分為對(duì)應(yīng)的子數(shù)組
需求:
將一個(gè)數(shù)組
let list = [1, 2, 3, 4, 5, 6, 7 , 8 ,9, 10, 11]
按照2個(gè)一組的子數(shù)組的形式返回芝加,如有多余的,則自己為一個(gè)子數(shù)組洁桌。
let targetList = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11]]
實(shí)現(xiàn)算法 時(shí)間復(fù)雜度:O(n)
//分割數(shù)組
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)
}
//有余數(shù), 加上最后一個(gè)
if hasSingleValue {
if let lastItem = list.last {
var subList: [T] = []
subList.append(lastItem)
targetList.append(subList)
}
}
print("\(targetList)")
return targetList
}