leetcode 35. Search Insert Position

来源:互联网 发布:网络家教收费标准 编辑:程序博客网 时间:2024/06/09 21:26

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

二分查找,没什么说的


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


accepted



0 0