LintCode【简单】60. 搜索插入位置 。代码及思路

题目要求:

给定一个排序数组和一个目标值,如果在数组中找到目标值则返回索引。如果没有,返回到它将会被按顺序插入的位置。

你可以假设在数组中无重复元素。

样例

[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(log(n)) time

思路:

因为给的是排序数组,所以很简单了,但是插入的时候要注意如果存在相等的数字,要插入到那个数字的前面。写完后发现挑战也完成了。

需注意:1.数组是空的情况;2.比A[0]小的情况;3.比A[A.size() - 1]大的情况;

代码:

class Solution {
public:
    /*
     * @param A: an integer sorted array
     * @param target: an integer to be inserted
     * @return: An integer
     */
    int searchInsert(vector<int> &A, int target) {
        // write your code here
        if(A.empty()) return 0;
        if(A[0] >= target) return 0;
        if(A[A.size() - 1] < target) return A.size();
        
        for(int i = 0; i < A.size() - 1; i++){
            if(A[i] < target && A[i + 1] >= target){
                return i + 1;
            }
        }
    }
};


猜你喜欢

转载自blog.csdn.net/limonsea/article/details/79267865