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) {
        int index=0;
        for(;index<n;index++)
        {
            if(target<=A[index]) break;
        }
        return index;
    }
};

阅读更多
想对作者说点什么?