給定一個排序數組和一個目標值,在數組中找到目標值,並返回其索引。若是目標值不存在於數組中,返回它將會被按順序插入的位置。數組
你能夠假設數組中無重複元素。ide
示例 1:code
輸入: [1,3,5,6], 5
輸出: 2排序
代碼實現索引
class Solution { public: int searchInsert(vector<int>& nums, int target) { int begin = 0; int end = nums.size()-1; int index = -1; while(index == -1) { int mid = (begin + end) / 2; if(nums[mid] == target) index = mid; else if(target < nums[mid]) { if(mid == 0 || target > nums[mid - 1] ) //先判斷mid的值,,順序不能反 index = mid; end = mid - 1; } else if(target > nums[mid]) { if( mid == nums.size()-1 ||target < nums[mid + 1] ) index = mid + 1; begin = mid + 1; } } return index; } };