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);
        }
    };
  • 相关阅读:
    HDU 5090 Game with Pearls
    HDU 1394 Minimum Inversion Number
    HDU 1698 Just a Hook
    POJ 2104 K-th Number
    UVA 1160
    HDU 5895 Mathematician QSC
    HDU 3294 Girls' research
    HDU 3068 最长回文
    PyCharm每日技巧-1
    如何一年考过日语一级
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4853208.html
Copyright © 2011-2022 走看看