35. Search Insert Position


Description Hints Submissions Discuss Solution
Discuss Pick One
Given a sorted array 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 may assume no duplicates in the array.
Here are few examples. [1,3,5,6] , 5 → 2 [1,3,5,6] , 2 → 1 [1,3,5,6] , 7 → 4 [1,3,5,6] , 0 → 0
Seen this question in a real interview before?  
 
Yes
 
挿入位置の検索
ソートされた配列とターゲット値が指定され、ターゲット値が見つかった場合はインデックス値が返され、ない場合はサイズに従って挿入され、挿入位置の下付き文字が返されます.
例えば:[1,3,5,6]、ターゲット5はあり、下付きは2
[1,3,5,6]ターゲット2はなく、位置を見つけて下に1箇所挿入
コード:
class Solution {
public:
    int searchInsert(vector& nums, int target) {
        int start=0,end=nums.size(),mid;//     ,     1,    
		while(start < end)
		{
			mid=(start+end)/2;
			if(nums[imd]>=target)
				end=mid;
			else
				start=mid+1;
		}
		return start;   
    }
};