zoukankan      html  css  js  c++  java
  • 【LeetCode】35. Search Insert Position (2 solutions)

    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

    解法一:线性查找(linear search)

    class Solution 
    {
    public:
        int searchInsert(int A[], int n, int target) 
        {
            if(n>0 && target <= A[0])
                return 0;
            for(int i = 0; i < n; i ++)
            {
                if(A[i] >= target)
                    return i;
            }
            return n;
        }
    };

    解法二:二分查找(binary search)

    class Solution {
    public:
        int searchInsert(int A[], int n, int target) {
            int low = 0;
            int high = n-1;
            while(low <= high)
            {
                int mid = low + (high-low) / 2;
                if(A[mid] == target)
                    return mid;
                else if(A[mid] > target)
                    high = mid - 1;
                else
                    low = mid + 1;
            }
            return low;
        }
    };

  • 相关阅读:
    NOIP 2018 day1 题解
    公司管理与信息化基础成熟度模型
    信息化成熟度整体评估模型
    审计抽样
    正态分布
    函证决策
    SALESORDERINCOME.QVW
    ERP上线通用模板
    可转换债券分拆
    luogu 1373 小a和uim之大逃离 dp
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/3834573.html
Copyright © 2011-2022 走看看