• 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;
    }
    
  • 相关阅读:
    dtclog
    求助解决 SQL SERVER 2005 log 事务日志增长太快的问题
    开辟第二战场
    c# 排序 求助
    怎样玩转3D
    爬楼梯问题迭代算法解!
    C++中类的继承方式的区别以及private public protected 范围
    想转c++
    PHP相关笔记
    常用快捷键
  • 原文地址:https://www.cnblogs.com/ZhongliangXiang/p/7353262.html
Copyright © 2020-2023  润新知