LeetCode 35. Search inserted position (java)

topic:

Given a sorted array and a target, find the object in the array, and returns its index. If the target is not present in the array, it will be returned in sequence inserted position.
You may assume that no duplicate elements 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
 

 

answer:

    See the sorted array, binary search first thought.

 

Code:

class Solution {
    public int searchInsert(int[] nums, int target) {     //模板
        int left = 0, right = nums.length - 1;
        while(left <= right) {
            int mid = (left + right) / 2;
            if(nums[mid] == target) {
                return mid;
            } else if(nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return left;
    }
}

 

Guess you like

Origin www.cnblogs.com/y1040511302/p/11250621.html