LeetCode-35. 搜索插入位置-Java

目录

 1.题目

 2.题解


 1.题目

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。

请必须使用时间复杂度为 O(log n) 的算法。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/search-insert-position

 2.题解

使用二分查找法

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

    }
}

猜你喜欢

转载自blog.csdn.net/m0_60494863/article/details/122130762