[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

[解题思路]

因为数组排过序了,所以只需要遍历一次,依次比较就可以了,相同就返回,如果更大,同样返回就是正确的插入位置。


class Solution {
public:
    int searchInsert(int A[], int n, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int nPos = 0;
        while (nPos < n) {
            if (A[nPos] < target)
                ++nPos;
            else
                return nPos;
        }
        return nPos;
    }
};


[源代码]

https://github.com/rangercyh/leetcode/blob/master/Search%20Insert%20Position


你可能感兴趣的:(leetcode解题报告)