LeetCode——35. Search for insertion position

Title description:

Given a sorted array and a target value, find the target value in the array and return its index. If the target value does not exist in the array, return the position where it will be inserted in order.
You can assume that there are 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

code show as below:

class Solution {
    
    
    public int searchInsert(int[] nums, int target) {
    
    
        int n = nums.length;
        if (target < nums[0]) {
    
    
            return 0;
        } else if (target > nums[n - 1]) {
    
    
            return n;
        } else if (target == nums[n - 1]) {
    
    
            return n - 1;
        } else {
    
    
            for (int i = 0; i < n - 1; i++) {
    
    
                if (nums[i] == target) {
    
    
                    return i;
                } else if (nums[i] < target && nums[i + 1] > target) {
    
    
                    return i + 1;
                }
            }
        }
        return 0;
    }
}

Results of the:
Insert picture description here

Guess you like

Origin blog.csdn.net/FYPPPP/article/details/114257379