LeetCode Week 1

35. 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


solution:
本题目是要求给一个有序数组和一个目标值,在数组中如果找到目标,则返回索引。如果没有,则返回如果按顺序插入的索引。我觉得可以直接遍历一遍数组,找到大于等于目标的值,则返回当前索引,若遍历完无满足要求的值,则说明目标值比数组中最后的值还大,需插入到数组最后一位,直接返回数组长度即可。

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        for(int i = 0; i < nums.size(); i++) {
            if(nums[i] >= target) {
                return i;
            }
        }
        return nums.size();
    }
};

至于优化部分可以采用二分法查找来优化它的时间复杂度。

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        if (nums.back() < target) return nums.size();
        int left = 0, right = nums.size() - 1;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) return mid;
            else if (nums[mid] < target) left = mid + 1;
            else right = mid;
        }
        return right;
    }
};

这里写图片描述

猜你喜欢

转载自blog.csdn.net/Xiouzai_/article/details/82463855