遇到一个需求:将一个数组分割为多个连续的子数组,比如将: 比如,数组中的数据为:
[1,2,3,5,6,8,9,10]可将数组分割为:[1,2,3]、[5、6]、[8,9,10]四个数组
核心代码如下
-(NSArray*)getNewArraysWithArray:(NSArray *)array{
NSMutableArray *newArrays = [NSMutableArray array];
NSMutableArray *subArray = [NSMutableArray array];
for (int i = 0; i < array.count; i++) {
if(i==0){
[subArray addObject:array[i]];
}else{
if([array[i] integerValue] - [array[i-1] integerValue] == 1){
[subArray addObject:array[i]];
}else{
[newArrays addObject:subArray];
subArray = [NSMutableArray array];
[subArray addObject:array[i]];
}
}
}
[newArrays addObject:subArray];
return [newArrays copy];
}