leetcode 35: Search Insert position

问题描述:
Given a sorted array (ascending order) of distinct integers 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.

一刷用暴力算法,线性时间复杂度:

class Solution {
    public int searchInsert(int[] nums, int target) {
        for (int i=0; i<nums.length; i++){
            if ((nums[i] == target) || (nums[i]>target)){
                return i;
            }   
        }
  //如果target大于最后一个数,那么之前的循环没法捕捉它,现在手动把它加在最后
        return nums.length;
    }
}

时间复杂度: O(n)

二刷用二叉搜索,代码如下:

class Solution {
    public int searchInsert(int[] nums, int target) {
        //step1: get the right_bound and left_bound
        int left=0;
        int right=nums.length-1;
        //don't loop when left=right, leave this equal situation for the final decison after loop
        //我习惯不把=加在循环条件里
        while(left<right){
            //这样计算mid绝对不会overflow
            int mid=left+(right-left)/2;
            //不够大?左标设为mid+1
            if(nums[mid]<target){
                left=mid+1;
            }
            //刚好?就是它了!
            else if(nums[mid]==target){
                return mid;
            }
            //超了?右标=mid (注意不是mid-1)
            else{
                right=mid;
            }
        }
        //if we reach here, meaning left=right, then we must make a decison
        //因为我没有在循环里处理left=right的问题,现在就要处理它:
        //注:这里用left和right都一样,因为执行到这一步肯定有left=right
        //若临界点刚好是目标值(范围缩小到最后,机会终于等来了)
        if(nums[left]==target){
            return left;
        }
        //若临界点小于目标值,则把这个值加在left后面
        else if (nums[left]<target){
            return left+1;
        }
        //若临界点大于目标值,则把这个值加在left前面(其实相当于占用left位置)
        else{
            return left;
        }
    }
}

时间复杂度: O(logn)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值