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;
    }
    
  • 相关阅读:
    Ubuntu20 修改网卡名称
    单臂路由实现不同vlan间通信
    配置trunk和access
    基于端口划分vlan
    Zabbix5.0服务端部署
    搭建LAMP环境部署opensns微博网站
    搭建LAMP环境部署Ecshop电商网站
    Zabbix 监控过程详解
    Zabbix agent端 配置
    Zabbix 监控系统部署
  • 原文地址:https://www.cnblogs.com/ZhongliangXiang/p/7353262.html
Copyright © 2011-2022 走看看