LeetCode 35. 搜索插入位置

LeetCode 35. 搜索插入位置

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。

你可以假设数组中无重复元素。

示例 1:

输入: [1,3,5,6], 5
输出: 2


知识点:

  • array_search(); // 在数组中根据值进行查找,并返回键的值

PHP代码:

function searchInsert($nums, $target) {
        // 方法一
        /*
        $ans = array_search($target, $nums);
        if ($ans === false) {
            for($i = 0; $i < count($nums); ++ $i) {
                if ($target < $nums[$i]) return $i;
            }
            return count($nums);
        }
        return $ans;
        */

        // 方法二
        for ($i = 0; $i < count($nums); ++ $i) {
            if ($target <= $nums[$i]) return $i;
        }
        return count($nums);
    }
原文地址:https://www.cnblogs.com/GetcharZp/p/11801519.html