美文网首页
Leetcode 35. Search Insert Posit

Leetcode 35. Search Insert Posit

作者: persistent100 | 来源:发表于2017-04-16 20:41 被阅读0次

    题目

    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) {
        int ans=0;
        for(ans = 0;ans < numsSize ; ans++)
        {
            if(nums[ans] >= target)
                break;
        }
        return ans;
    }
    

    相关文章

      网友评论

          本文标题:Leetcode 35. Search Insert Posit

          本文链接:https://www.haomeiwen.com/subject/epxzattx.html