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.

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

题意:给定有序数组和目标元素,找该元素的插入位置,如果该元素没有在数组中,找到它应该插入的位置(保持原数组有序)

解决思路:二分查找

代码:

public class Solution {
    public int searchInsert(int[] nums, int target) {
        int count = nums.length;
        int left = 0;
        int step = 0;
        int mid = 0;

        while(count > 0){
            step = count >> 2;
            mid = left + step;

            if(nums[mid] < target){
                left = mid + 1;
                count -= (step + 1);
            }else{
                count = step;
            }
        }

        return left;
    }
}

你可能感兴趣的:(LeetCode题解:Search Insert Position)