zoukankan      html  css  js  c++  java
  • 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.

    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
    

    自家媳妇:
    (O(n)) time, (O(1)) space. 忘记使用 (Binary Search) 了.
    请记住一件事,有序数组操作,必用(Binary Search).

    int searchInsert(vector<int>& A, int target) {
        if (A.size() == 0) return 0;
        if (A[A.size() - 1] < target) return A.size();
        if (A[0] >= target) return 0;
        int i = 1;
        while (i < A.size()) {
            if (A[i] == target) return i;
            if (A[i - 1] < target && A[i] > target) return i;
            i++;
        }
    

    自己的二分查找.
    (O(logn)) time, (O(1)) space.
    经验:

    1. 设定条件 while(lo < hi)
    2. 退出 while 后,lo 一定等于 hi.
    3. 在循环外,应再次判断A[lo]所指向的值, 因为这个值前面没读取过.
    int searchInsert(vector<int>& A, int target) {
        int n = A.size();
        if (n == 0) return 0;
        if (A[n - 1] < target) return n;
        if (A[0] >= target) return 0;
        int lo = 0, hi = n - 1, mid;
    
        while (lo < hi) {
            mid = (lo + hi) / 2;
            if (A[mid] == target) return mid;
            if (A[mid] < target)
                lo = mid + 1;
            if (A[mid] > target)
                hi = mid - 1;
        }
        // lo == hi
        if (A[lo] < target) return lo + 1;
        else return lo;
    }
    

    人家媳妇:
    (O(logn)) time, (O(1)) space. 用了二分查找.

    //TODO
    int searchInsert(vector<int>& nums, int target) {
        int n = nums.size();
        if (n == 0) return 0;
        int i = 0, j = n - 1;
        while (i < j - 1) {
            int mid = i + (j - i) / 2;
            if (nums[mid] == target) return mid;
            if (nums[mid] > target) j = mid;
            else i = mid;
        }
        if (target <= nums[i]) return i;
        if (target <= nums[j]) return j;
        return j + 1;
    }
    
  • 相关阅读:
    坚持
    随笔
    C++:对象和类
    STEP7 V14 安装和激活
    c++:cout
    C 格式化字符串处理函数
    WIn:消极处理机制
    Python:requests发送json格式数据
    Python:logging日志功能的基本使用
    PLC:西门子测试
  • 原文地址:https://www.cnblogs.com/ZhongliangXiang/p/7353262.html
Copyright © 2011-2022 走看看