首页 > 代码库 > 【LeetCode】Search Insert Position

【LeetCode】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


     思路:

     给定一个有序数组,和一个目标元素,如果目标元素存在,则给出其在数组中对应的下标。不存在则返回一个整数,表明目标元素应该插入到数组中的位置。

     很简单的一道题,只要遍历数组,有以下情况:

     1. 如果找到该元素,直接返回其下标

     2. 遇到第一个比它大数,返回这个数的下标。

     3. 找不到比它大的数,那么应该插入到最后,返回 n。

     情况 1 2 可以写在一起。


     代码:

     C++:

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

     Python:

class Solution:
    # @param A, a list of integers
    # @param target, an integer to be inserted
    # @return integer
    def searchInsert(self, A, target):
        n = len(A)
        for i in range(0,n):
            if A[i] >= target:
                return i
        return n

【LeetCode】Search Insert Position