leetcode -- Search Insert Position

Search Insert Positioncode

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

You may assume no duplicates in the array.leetcode

Example 1:get

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

Example 2:it

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

Example 3:io

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

Example 1:class

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

Solution:sort

class Solution {
    public int searchInsert(int[] nums, int target) {
        if (nums==null){
            return 0;
        }
        if(target<nums[0]){
            return 0;
        }
        if(target>nums[nums.length-1]){
            return nums.length;
        }
        int left = 0;
        int right = nums.length;

        while(left<=right){
            int mid = (left + right) /2;
            if(target==nums[mid]){
                return mid;
            }else if(target>nums[mid] && target<nums[mid+1]){
                return mid+1;
            }else if(target > nums[mid]){
                left = mid+1;
            }else{
                right = mid-1;
            }
        }
        return -1;
    }
}
相關文章
相關標籤/搜索