[C语言][LeetCode][35]Search Insert Position

题目

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

标签

Array、Binary Search

难度

适中

分析

题目意思是给定一个排好序的整型数组和一个整型,将这个数按序插入,返回插入的坐标。这道题很简单,不明白为啥难度是适中。

C代码实现

int searchInsert(int* nums, int numsSize, int target) {
    int i = 0;

    for(i=0; i<numsSize; i++)
    {
        if(nums[i] == target)
            return i;
        else if(nums[i] > target)
            return i;
    }
}

你可能感兴趣的:(LeetCode,算法,C语言)