美文网首页
【剑指offer】和为定值的两个数

【剑指offer】和为定值的两个数

作者: 杨晓晨 | 来源:发表于2017-11-15 17:04 被阅读0次

题目描述:

输入一个递增排序的数组和一个数字S,在数组中查找两个数,是的他们的和正好是S,输出任意一对即可

输入:

每个测试案例包括两行:
第一个参数包含n个整数数组,每个数组均为NSNumber类型。数组的长度限制在 1M 以内。
第二个参数包含一个整数value,value表示两数之和。

输出:

对应每个测试案例,输出两个数,小的先输出。如果找不到,则输出“-1 -1”

思想:

类似快速排序,将两边不合理的值去掉,然后查找中间的,先查找右边,再查找左边
代码:

+ (BOOL)equalSubWithArray:(NSArray *)array value:(NSInteger )value {
    if (array == nil || array.count == 0) {
        return false;
    }
    NSInteger left = 0;
    NSInteger right = array.count - 1;
    NSNumber *tempRightNumber = array[right];//取出数组最右侧的值
    NSInteger tempRightValue = tempRightNumber.integerValue;
    while (tempRightValue > value) {//待比较值与最右侧值做比较,一直找到比待比较值小的数,这样会比较节约时间
        --right;
        tempRightNumber = array[right];
        tempRightValue = tempRightNumber.integerValue;
    }
    NSNumber *tempLeftNumber = array[left];
    NSInteger tempLeftValue = tempLeftNumber.integerValue;
    while (tempLeftValue + tempRightValue < value) {//去掉最小的不可能用到的数据
        ++left;
        tempLeftNumber = array[left];
        tempLeftValue = tempLeftNumber.integerValue;
    }
    while (left < right) {
        if (tempLeftValue + tempRightValue == value) {//如果想等自然最好,打印两个值
            NSLog(@"最小的值为%zu, 最大的值为%zu",tempLeftValue, tempRightValue);
            return true;
        } else if (tempLeftValue + tempRightValue > value) {//玩大了那右边指针前移
            --right;
        } else {
            ++left;//玩小了左边指针后移
        }
    }
    
    return false;
}

GitHub : https://github.com/XiaoChenYung/ArrowToOffer/blob/master/ArrowToOffer/EqualSum.m

相关文章

网友评论

      本文标题:【剑指offer】和为定值的两个数

      本文链接:https://www.haomeiwen.com/subject/yaccvxtx.html