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.

Example 1:

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

Example 2:

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

Example 3:

Input: [1,3,5,6], 7
Output: 4

Example 4:

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

代码:

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        if (nums.size() == 0)return 0;
	int i = 0, j = nums.size() - 1, mid = -1;

	if (target < nums[i])return i;
	if (target > nums[j])return j+1;
	
	while (i <= j) {
		mid = (i + j) / 2;
		if (nums[mid] > target) {
			j = mid - 1;
		}
		else if (nums[mid] < target) {
			i = mid + 1;
		}
		else {
			return mid;
		}
	}

	if (nums[i] > target) return i;
	if (nums[i] < target)return i + 1;
    
    return 0;
    }
};

注:

1、考虑结尾的插入

2、while的时候一定不能遗漏i=j的情况,需要写成while(i<=j)

3、不要出现任何形式的可能没有return 的情况,否则会编译报错

猜你喜欢

转载自blog.csdn.net/qq_35455503/article/details/85683032