035 - Search Insert Position

来源:互联网 发布:php上传图片到数据库 编辑:程序博客网 时间:2024/05/20 10:55

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.

Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0



给定一个排好序的数列,假设元素没有重复的,给定一个target,找到这个target对应的下标,如果找不到,返回target插入位置的下标

int searchInsert(int* nums, int numsSize, int target) {int left = 0, right = numsSize - 1, mid;while(left <= right) {mid = (left + right) / 2;if(nums[mid] < target) left = mid + 1;else right = mid - 1;}return left;}


0 0