35. Search Insert Position(easy array)

180 阅读1分钟

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) {

        int position = 0;
        for (int i = nums.size() - 1; i >= 0; i--) {
            if (target == nums[i]) {
                position = i;
                break;
            }
            else if (target > nums[i]) {
                position = i + 1;
                break;
            }
        }
        return position;
    }
};

感觉在写题的时候,思路还不是很清晰,没有及时想到要从后向前找到合适的位置。如果从前向后找,假设数组中的元素均小于target的值,那这样就会使判断条件复杂很多。

同时还想到了使用二分的方法来实现。在用二分法实现的时候,还是遇到了一些问题:1、如何处理数组下标为0,size()-1的元素;2、需要考虑end < begin的情况。

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