banner
ekko

ekko's blog

时间不在于你拥有多少,而在于你怎样使用
github
xbox
email

Search for insertion point

Description#

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

You may assume no duplicates in the array.

Example 1:

Input: [1,3,5,6], 5
Output: 2

Example 2:

Input: [1,3,5,6], 2
Output: 1

Example 3:

Input: [1,3,5,6], 7
Output: 4

Example 4:

Input: [1,3,5,6], 0
Output: 0

Approach#

  • Traverse the array, if the current element is greater than or equal to the target value, return the index
  • Return the size of the array at the end of traversal, indicating insertion at the end of the array
int searchInsert(int* nums, int numsSize, int target){
    for(int i=0;i<numsSize;i++)
        if(nums[i] >= target)
            return i;
    return numsSize;
}
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.