有没有一种简单的方法可以将数字数组转换为按顺序排列数字的数组?
NSArray *numbers = @[@1,@2,@5,@3];
// Transformed arrays
//NSArray *numbersInSequence = @[@1,@2,@3];
//NSArray *numbersInSequence2 = @[@5];
编辑:
我修改了理查德答案中的代码以使其正常工作。
NSArray *arraysBySplittingNumbersInOrder(NSArray *input) {
// sort 'input'
input = [input sortedArrayUsingSelector:@selector(compare:)];
NSMutableArray *results = [NSMutableArray array];
if (input.count) {
int start = 0;
int last = INT_MIN;
for (int i = 0; i < input.count; i++) {
BOOL lastItem = i == input.count - 1;
// The first item of the array
if (i == 0) {
if (lastItem) {
[results addObject:input];
break;
}
last = [input[i] intValue];
continue;
}
int cur = [input[i] intValue];
if (cur != last + 1) {
// pull out the next array
[results addObject:[input subarrayWithRange:NSMakeRange(start, i - start)]];
start = i;
}
// The last item of the array
if (lastItem) {
[results addObject:[input subarrayWithRange:NSMakeRange(start, i - start + 1)]];
}
last = cur;
}
}
return results;
}