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;
    }
};

【LeetCode】35. Search Insert Position (2 solutions)

 

解法二:二分查找(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;
    }
};

【LeetCode】35. Search Insert Position (2 solutions)

相关文章:

  • 2021-09-21
  • 2021-09-29
  • 2021-11-08
  • 2022-03-06
  • 2021-11-27
  • 2022-12-23
  • 2021-10-18
猜你喜欢
  • 2022-01-03
  • 2021-07-12
  • 2021-08-12
  • 2021-08-09
  • 2021-07-12
  • 2021-09-27
  • 2021-09-07
相关资源
相似解决方案