2020年7月11日 星期六

LeetCode 35. Search Insert Position [Easy] [C++] 解題筆記

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.


EX:

        Input: [1,3,5,6], 5

        Output: 2
想法:
    Sorted array 裡找數字 => 直接 binary search 拉!

完整程式碼:
class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int low = 0;
        int high = nums.size()-1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (nums[mid] == target) {
            	return mid;
            }
            else if (nums[mid] > target) {
                high = mid - 1;
            }
            else {
                low = mid + 1;
            }
        }
        
        return low;
    }
};

沒有留言:

張貼留言