剑指 Offer II 068. 查找插入位置(35. 搜索插入位置)

题目:

 

 

思路:

【1】直接二分查找

代码展示:

//时间0 ms击败100%
//内存40.9 MB击败74.5%
class Solution {
    public int searchInsert(int[] nums, int target) {
        int n = nums.length;
        int left = 0, right = n - 1, ans = n;
        while (left <= right) {
            int mid = ((right - left) >> 1) + left;
            if (target <= nums[mid]) {
                ans = mid;
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return ans;
    }
}

 

posted @ 2023-03-01 16:48  忧愁的chafry  阅读(9)  评论(0编辑  收藏  举报