LeetCode--Merge Sorted Array

Difficulty: Easy

【题目】Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.

翻译

合并有序数组
难度系数:简单
合并两个有序数组。

// 时间复杂度n

[self getArrayA:@[@"1",@"4",@"7",@"10",@"15"] B:@[@"1",@"4",@"5",@"16",@"110"]];

- (NSArray *)getArrayA:(NSArray<NSString *> *)a B:(NSArray<NSString *> *)b {
    
    NSMutableArray *c = [[NSMutableArray alloc] init];
    int aInt = 0;
    int bInt = 0;
    for (int i = 0; i < a.count+b.count; i++) {

        if (aInt == a.count) {
            
            [c addObject:b[bInt]];
            bInt ++;
        }else if (bInt == b.count) {
            
            [c addObject:a[aInt]];
            aInt ++;
        }else {
            
            if (a[aInt].integerValue >= b[bInt].integerValue) {
                
                [c addObject:b[bInt]];
                bInt ++;
            }else {
                [c addObject:a[aInt]];
                aInt ++;
            }
        }
    }
    
    return c;
}

记住算法最重要的一点,永远先处理特殊情况。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容