Leetcode PHP题解--D138 35. Search Insert Position


D138 35. Search Insert Position

题目链接

35. Search Insert Position

题目分析

给定一个有序数组和一个数字,返回这个数字出现的位置。如果这个数字没有出现,那么返回这个数字本该出现的位置。

解题思路

这题也很简单,逐个遍历,直到后面的数字大于给定的数字就可以了。

最终代码

<?php
class Solution {

    /**
     * @param Integer[] $nums
     * @param Integer $target
     * @return Integer
     */
    function searchInsert($nums, $target) {
        foreach($nums as $index => $num){
            if($num == $target){
                return $index;
            }
            if($num > $target){
                return max(0,$index);
            }
        }
        return $index+1;
    }
}

若觉得本文章对你有用,欢迎用爱发电资助。


点赞 取消点赞 收藏 取消收藏

<< 上一篇: Leetcode PHP题解--D137 27. Remove Element

>> 下一篇: Leetcode PHP题解--D139 38. Count and Say