--- title: 'LeetCode 35. Search Insert Position' disqus: hackmd --- # LeetCode 35. Search Insert Position ## Description Given a sorted array of distinct integers 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 must write an algorithm with O(log n) runtime complexity. ## Example Input: nums = [1,3,5,6], target = 5 Output: 2 Input: nums = [1,3,5,6], target = 2 Output: 1 ## Constraints 1 <= nums.length <= 10^4^ -10^4^ <= nums[i] <= 10^4^ nums contains distinct values sorted in ascending order. -10^4^ <= target <= 10^4^ ## Answer 因為要找target可插入的位置,所以只要找到第一個大於等於target的位置即可,用while來往下尋找,他會停在nums第一個大於等於target的位置,直接return即可。 ```Cin= //2022_03_29 int searchInsert(int* nums, int numsSize, int target){ int i = 0; while(i < numsSize && nums[i] < target){i++;} return i; } ``` ## Link https://leetcode.com/problems/search-insert-position/ ###### tags: `Leetcode`