The two commonly used algorithm combined iOS ordered array, the required time complexity is 0 (n)

 

Ideas: to conventional thinking: a first array as an array combined, then traverse each element of the second array, one comparisons, until you find the right, is inserted into it;

  Simple idea: the leading element of an array of set C, B and A comparison of the array, find the minimum, it is placed in an array C, in order to proceed.

code show as below:

- (NSArray *)mergeOrderArrayWithFirstArray: (NSMutableArray *)array1 secondArray: (NSMutableArray *)array2 {
    // 全为空不处理
    if (!array1.count && !array2.count) {
        return @[];
    }
    // 一个为空返回另外一个
    if (!array1.count) {
        return array2;
    }
    if (!array2.count) {
        return array1;
    }
    NSMutableArray *endArray = [NSMutableArray array];
    while (1) {
        if ([array1[0] integerValue] < [array2[0] integerValue]) {
            [endArray addObject:array1[0]];
            [array1 removeObjectAtIndex:0];
        }else  {
            [endArray addObject:array2[0]];
            [array2 removeObjectAtIndex:0];
        }
        if (!array1.count) {
            [endArray addObjectsFromArray:array2];
            break;
        }
        if (!array2.count) {
            [endArray addObjectsFromArray:array1];
            break;
        }
    }
    return endArray; 
}
 

 

Guess you like

Origin www.cnblogs.com/jgCho/p/11203508.html