本文主要是介绍035 - Search Insert Position,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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;
}
这篇关于035 - Search Insert Position的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!