Will I leave?.|

Canyooo

园龄:3年6个月粉丝:1关注:1

【LeetCode】#35. 搜索插入位置

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

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

 

 方法一:数组遍历

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

方法二:二分法

复制代码
class Solution {
    public int searchInsert(int[] nums, int target) {
        int n=nums.length;
        int low=0;
        int high=n-1;
        int mid;
        while(low<=high){
            mid=(low+high)/2;
            if(target<nums[mid]){
                high=mid-1;
            }else if(target>nums[mid]){
                low=mid+1;
            }else if(target==nums[mid]){
                return mid;
            }
        }
        return high+1;
    }
}
复制代码

知识点:

总结:

判断大小的题目不能只用遍历,有时应使用其他算法增加效率。

本文作者:Canyooo

本文链接:https://www.cnblogs.com/canyooo/p/15255693.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Canyooo  阅读(24)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 黑洞里 方大同
黑洞里 - 方大同
00:00 / 00:00
An audio error has occurred.

Not available