LeetCode 35. Search Insert Position

来源:互联网 发布:office卸载软件 编辑:程序博客网 时间:2024/06/08 19:57

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

在一个有序数组中寻找目标值,如果找到就返回下标,找不到就返回它在有序数组中应该插入的位置。
很简单的一道二分搜索的题目,直接上代码!
You may assume no duplicates in the array.

int searchInsert(vector<int>& nums, int target) {        if (nums.size() == 0) return 0;        int low = 0, high = nums.size() - 1, mid;        while (low <= high)        {            mid = (low + high) / 2;            if (nums[mid] < target) low = mid + 1;            else if (nums[mid] > target) high = mid - 1;            else return mid;        }        //此时low>high        return low;    }
原创粉丝点击