面接準備中。object-CIe input =[1,2,2,1,2,3,3,4] output =[1,2,1] を使用して、「配列から連続した重複を排除する最速の方法」という質問の解決策を見つけよう,2,3,4]
配列内アプローチの場合: 配列内の要素をループします。要素 == 前の要素の場合は、それを削除し、他のすべての要素を再調整してステップを下げます。
別の配列を使用できるアプローチの場合。要素 == 前の要素の場合、新しい「一意の配列」に追加しないでください。それ以外の場合は、一意の配列に追加します。
より良い解決策はありますか?コードは以下です。可能な最適化はありますか?
別の配列の使用
//Pseudocode for sucessive dup elimination when using another array
//
//duplicateLessArray = empty array
//previous element = not set
//
//for (loop through each element in origArray)
// if(previous element == not set or element != previous element)
// set previousElement = element
// add element to duplicateLessArray
//
NSMutableArray *duplicateLessArray ;
duplicateLessArray = [[NSMutableArray alloc] init] ;
for (NSNumber *nextNumber in origArray)
{
if ([nextNumber intValue] != [[duplicateLessArray lastObject] intValue])
{
[duplicateLessArray addObject:nextNumber] ;
}
}
NSLog(@"Duplicate less array = %@",duplicateLessArray) ;
同じ配列の使用
//Pseudocode for in array sucessive dup elimination
//
//previous element = not set
//
//for (loop through each element in origArray)
// if(previous element == not set or element != previous element)
// set previousElement = element
// else
// delete it from origArray
// move back all elements by 1
NSInteger numElementsInDupLessArray = 0 ;
NSNumber *prevElement ;
for (NSNumber *nextNumber in [origArray copy])
{
if (numElementsInDupLessArray == 0 || [nextNumber intValue] != [prevElement intValue])
{
prevElement=nextNumber ;
numElementsInDupLessArray++;
}
else
{
[origArray removeObjectAtIndex:numElementsInDupLessArray] ;
}
}
NSLog(@"Duplicate less array = %@",origArray) ;