0

准备面试。尝试使用objective-CIe input = [1,2,2,1,2,3,3,4] output = [1,2,1来解决“从数组中消除连续重复的最快方法”问题,2,3,4]

  1. 对于数组内方法:遍历数组中的元素,如果元素 == 前一个元素,则将其删除并重新调整所有其他元素以向下移动。

  2. 对于我们可以使用另一个数组的方法。如果 element == 前一个元素,则不要将其添加到新的“唯一数组”中,否则将其添加到唯一数组中。

有没有更好的解决方案?代码如下。可以进行任何优化吗?

使用另一个数组

//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) ;
4

1 回答 1

2

数组内方法有优化:

而不是一个接一个地删除元素(这可能会导致 O(n^2) 复杂性)只是移动单个元素。
伪代码:

numOfRemoved = 0
GoodValue = A[0]
for i = 1 to arrayEnd //note start from 2nd element
  if A[i] = GoodValue then
    numOfRemoved++
  else
    GoodValue = A[i]
    A[i-numOfRemoved] = A[i]
Resize array once to (Length - numOfRemoved)

示例(' 表示当前元素,nr 为 numOfRemoved)

[5 5 1 7 7 7 4]   nr = 0  ; 5 stays at index 0
[5 '5 1 7 7 7 4]  nr = 0->1
[5 5 '1 7 7 7 4]  nr = 1 ; 1 goes to index 2-1 = 1
[5 1 1 '7 7 7 4]  nr = 1 ; 7 goes to index 2  
[5 1 7 7 '7 7 4]  nr = 1->2
[5 1 7 7 7 '7 4]  nr = 2->3
[5 1 7 4 7 7 '4]  nr = 3 ; 4 goes to index 6-3 = 3
[5 1 7 4]         resize
于 2016-04-17T03:58:59.193 回答