Monday, January 7, 2013

Search Insert Position -- Binary Search

Problem:

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.


Solution:

class Solution {
public:
    int searchInsert(int row_mat[], int row, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int beg = 0, end = row - 1, index;

        while (beg <= end) {
            index = (beg + end)/2;
            if (row_mat[index] == target) {
                return index;
            } else if (row_mat[index] > target) {
                end = index - 1;
            } else {
                beg = index + 1;
            }
        }
        return beg;
    }
};

No comments:

Post a Comment