35-m-Search Insert Position

来源:互联网 发布:js split数组 编辑:程序博客网 时间:2024/06/16 14:03

上一题的变种。不给你相等的target了,看你怎么插。这道题用二分还有点道理因为是找点,上一题找范围的实在不知二分有啥优势。话说这道题一开始我也是直接循环暴力找点,一次就AC耗时竟然还是0ms。觉得没挑战又用二分,于是在边界值上费了半天时间AC了,耗时还是4ms,有点作。

暴力:

int searchInsert(int* nums, int numsSize, int target) {    int result = -1;    for (int i = 0; i < numsSize; i++) {        if (nums[i] >= target) {            result = i;            break;        }    }    if (result == -1)        result = numsSize;        return result;}

二分:

int fix_searchInsert(int* nums, int numsSize, int target) { // 1,3,5;2    int result = -1;    int low = 0, high = numsSize - 1;    int index = 0;    while (low <= high) {        index = (low + high) / 2;        if (nums[index] >= target) {            high = index - 1;        }        else            low = index + 1;    }    if (low > high && nums[index] < target) //如果从右边出去,则说明target比nums[index]大,所以应在index右边        result = index + 1;    else if (high < low && nums[index] >= target) //如果从左边出去,则表示target比nums[index]小或等于,因此就插在index处        result = index;        return result;}


0 0
原创粉丝点击