[LeetCode]Search Insert Position
Search Insert Position 給一個排序且沒有重複的整數陣列,尋找目標值在陣列哪個位置,如果沒有結果則回傳該整數應該在的位置。 Example 1 Input: nums = [1,3,5,6], target = 5 Output: 2 Example 2 Input: nums = [1,3,5,6], target = 2 Output: 1 Example 3 Input: nums = [1,3,5,6], target = 7 Output: 4 解法 class Solution { /** * @param Integer[] $nums * @param Integer $target * @return Integer */ function searchInsert($nums, $target) { $count = count($nums); $data = 0; for ($i = 0; $i < $count; $i++) { if ($target == $nums[$i]) { $data = $i; break; } if ($target > $nums[$i]) { $data = $i + 1; } } return $data; } }