[LeetCode] Search Insert Position

https://leetcode.com/problems/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

解法一:

class Solution {

public:

    int searchInsert(vector<int>& nums, int target) {

         int left = 0, right = nums.size() - 1, middle;

         // 保证可以缩小范围,当只剩下一个数的时候退出循环

         while (left < right) {

             middle = (left + right) >> 1;

             if (target == nums[middle]) {

                 return middle;

             } else if (target > nums[middle]) {

                 left = middle + 1; // 当只有两个数的时候,由于middle会指向左边的数字,为了确保一定可以缩小范围,因此此处令middle+1

             } else if (target < nums[middle]) {

                 right = middle;

             }

         }

         

         if (target == nums[left]) {

             return left;

         } else if (target > nums[left]) {

             return left + 1;

         } else if (target < nums[left]) {

             return left;

         }

    }

}

解法二:

class Solution {

public:

    int searchInsert(vector<int>& nums, int target) {

        int left = 0, right = nums.size() - 1, middle;

        while (left + 1 < right) {

            middle = (left + right) >> 1;

            if (target == nums[middle]) {

                return middle;

            } else if (target < nums[middle]) {

                right = middle;

            } else {

                left = middle;

            }

        }

        

        // 如果退出循环,只剩下两个数

        if (target <= nums[left]) {

            return left;

        } else if (nums[left] < target && target <= nums[right]) {

            return left + 1;

        } else if (target > nums[right]){

            return right + 1;

        }

    }

};

你可能感兴趣的:(LeetCode)