给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素最多出现两次,返回移除后数组的新长度。
// Remove Duplicates from Sorted Array II
-(NSInteger)removeElementInSortedArrayII:(NSMutableArray <NSNumber *> *)array
{
NSInteger max = 2;
if (array.count <= max) {
return array.count;
}
NSInteger length = 0;
NSInteger repeatCount = 0;
for (int i=1; i<array.count; i++) {
if (array[length].integerValue == array[i].integerValue) {
if (repeatCount < 2) {
repeatCount ++;
array[++length] = array[i];
}
} else {
array[++length] = array[i];
repeatCount = 1;
}
NSLog(@"%@",array);
}
length ++;
if (array.count > length) {
[array removeObjectsInRange:NSMakeRange(length, array.count - length)];
}
NSLog(@"%@",array);
return length;
}
网友评论