zoukankan      html  css  js  c++  java
  • 35. Search Insert Position (Array; Divide-and-Conquer)

    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.

    Here are few examples.
    [1,3,5,6], 5 → 2
    [1,3,5,6], 2 → 1
    [1,3,5,6], 7 → 4
    [1,3,5,6], 0 → 0

     思路:排好序的数列用二分法进行搜索。二分法查找到的最后那个元素,要么是target,要么是紧邻target左侧或右侧的元素。
    class Solution {
    public:
        int searchInsert(vector<int>& nums, int target) {
            if(nums.size()==0) return 0;
            return binarySearch(nums,0,nums.size()-1,target);
        }
        
        int binarySearch(vector<int>& nums, int start, int end, int target){
            if(start==end){
                if(target <= nums[start]) return start;
                else return start+1;
            }
            
            int mid = start + ((end-start)>>1);
            if(target <= nums[mid]) return binarySearch(nums,start,mid,target);
            else return binarySearch(nums,mid+1,end,target);
        }
    };
  • 相关阅读:
    Hive安装
    hbase安装
    Spring boot 出现的时间
    RESTful Web API 实践
    Java的进阶之道
    Spring boot 注解简单备忘
    使用 xshell 登录 Windows 的 linux 子系统
    Nginx 实用配置
    跟着大彬读源码
    跟着大彬读源码
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4853208.html
Copyright © 2011-2022 走看看