LeetCode【#35】Search Insert Position(搜索插入位置)

题目链接:

点击跳转

 

题目:

Given a sorted array 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.

You may assume no duplicates 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

题目分析:

给定一个已排好序(升序)数组,和一个数值。如果数组里有同这个数值的,那就返回其下标。如果数组中没有这个数,返回它将会被按顺序插入的位置。

 

解题思路:

用的是Java语言,所以一开始的思路。

思路一、Java中有一个函数:Arrays.binarySearch(),刚好可以实现这个要求,这个函数的前提要求就是数组是排序的。返回值,如果有这个数,就返回下标。如果没有这个数,就返回 - 应插入位置 -1。所以直接使用函数库,如果返回值是小于0,那就取相反数再减1。

思路二、如果不能使用函数,那就要自己实现这个功能,首先想到的就是遍历该数组,如果有相等的值,那就返回下标;没有相等的值,那就找到大于前一个数和小于后一个数的后一个数的下标,就是返回值。这里主要要考虑几个特殊情况:①没有这个值到插入值在最开始和最后面。还有因为没有这个值要找有前后都有这个数,所以如果遍历下标应该从0到倒数第二个数(这样子后一个数才存在),所以最后一个数无法遍历到,因此还加上一个特殊情况②最后一个值刚好和要求的数值相等,那就返回最后一个值得下标

这个的时间复杂度是O(n)。

思路三、上面有了一个线性时间复杂度了,而根据思路一调用的函数也可以知道,那个函数使用的是二分查找,因此思路三就也考虑使用二分查找。

此时时间复杂度O(logn)。

 

AC代码:(Java)

思路一、

class Solution {
    public int searchInsert(int[] nums, int target) {
        int res = Arrays.binarySearch(nums, target);
        if(res < 0)
            res = -res-1;
        
        return res;
    }
}

思路二、

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

        return 0;
    }
}

思路三、

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值