LeetCode Search Insert Position (二分查找)

題意

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
給定一個有序數組和一個目標值,查找出目標值在數組中出現的位置,如果沒有出現,則返回它應該插入的位置。

解法

二分查找,記錄mid值,查找結束後判斷nums[mid] == target,如果相等的話就返回,不相等的話判斷這個位置上的值是不是比target大,如果比它大那麼target就直接插在mid這個位置,比target小的話就把target插入到下一個位置。

class Solution
{
public:
    int searchInsert(vector<int>& nums, int target)
    {
	    int	left = 0;
	    int	right = nums.size() - 1;
	    int	mid = 0;
	    int	index = 0;

	    while(left <= right)
	    {
		    mid = (left + right) >> 1;
		    if(nums[mid] == target)
		    {
			    index = mid;
			    break;
		    }
		    else
			    if(nums[mid] < target)
				    left = mid + 1;
			    else
				    right = mid - 1;
	    }
	    if(nums[index] == target)
		    return	index;
	    if(target > nums[mid])
		    return	mid + 1;
	    else
		    return	mid;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章