leetcode刷题笔记三十五 搜索插入位置

leetcode刷题笔记三十五 搜索插入位置

源地址:35. 搜索插入位置

问题描述:

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

你可以假设数组中无重复元素。

示例 1:

输入: [1,3,5,6], 5
输出: 2
示例 2:

输入: [1,3,5,6], 2
输出: 1
示例 3:

输入: [1,3,5,6], 7
输出: 4
示例 4:

输入: [1,3,5,6], 0
输出: 0

代码补充:

//本题较为简单,从左向右遍历 找到插入位置
//或者可以将该元素与数组合并,使用排序方法,再返回位置
//时间复杂度基本是O(n)
object Solution {
    def searchInsert(nums: Array[Int], target: Int): Int = {
        var left = 0
        val right = nums.length - 1
        if (nums(left) >  target) return 0
        if (nums(right) < target) return right+1
        while(nums(left) < target) left += 1
        println(left)
        return left  
    }
}

//或者使用二分法,这么复杂度更低
object Solution {
    def searchInsert(nums: Array[Int], target: Int): Int = {
        def binarySearch(left:Int, right:Int):Int = {
            if (left > right)   left
            else{
                val mid = (left + right)/2
                if (nums(mid) < target) binarySearch(mid+1, right)
                else binarySearch(left,mid-1)
            }
        }

        binarySearch(0, nums.length-1)
    }
}
posted @ 2020-05-12 00:38  ganshuoos  阅读(110)  评论(0编辑  收藏  举报