Leetcode 35. Search Insert Posit

2017-04-16  本文已影响0人  persistent100

题目

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;
}
上一篇下一篇

猜你喜欢

热点阅读