LeetCode brush title series -35. Search Insert Position

1. Title Description

English version:

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

Chinese Version:

Ordered array to a target value and, if present, is returned to its subscript,

If not, it should be inserted in the array location is returned.

Suppose the array does not exist duplicate elements.

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

2. Solution

2.1 Solution 1

Ideas:

    public static int searchInsert1(int[] nums, int target) {
        for(int i = 0;i < nums.length;i++){
            if (nums[i] >= target){
                return i;
            }
        }
        return nums.length;
    }

Running on LeetCode results:

2.2 Method 2

Ideas:

    public static int searchInsert(int[] nums, int target) {
        if(target > nums[nums.length - 1]){
            return nums.length;
        }
        int left = 0;
        int right = nums.length - 1;
        while (left < right){
            int middle = left + (right - left) / 2;
            if (target < nums[middle]){
                right = middle;
            }else if(target > nums[middle]){
                left = middle + 1;
            }else {
                return middle;
            }
        }
        return right;
    }

Running on LeetCode results:

3. Test

Locally, I simply wrote a main function to test it. But these codes are passed on LeetCode run of.

    public static void main(String[] args) {
        int[] nums = {1,3,5,6};
        int target = 2;
        int result = searchInsert(nums,target);
        System.out.println(result);
    }
No personal welcome attention to the public, can directly scan the following QR code or micro-letter search for "Amauri talk technology."

Guess you like

Origin www.cnblogs.com/limaodeng/p/12358989.html
Recommended