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);
        }
    };
  • 相关阅读:
    索引查找Java实现
    经典算法之折半查找
    进制转换问题
    排序算法总结之希尔排序
    自己写的栈
    排序问题Java
    画柱状图Java
    一些值得看的性能优化的文章
    理解 BFC
    canvas
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4853208.html
Copyright © 2011-2022 走看看