본문 바로가기

풀어본 Algorithm 문제 정리

[OJ.leetcode] Search Insert Position

https://oj.leetcode.com/problems/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 start = 0;

        int end = n-1;

        findNeedle(A,start, end, target);

    }

    

    int findNeedle(int input[], int start, int end, int needle) {

        if(start > end) return -1;

        

        if(start <= end) {

            int mid = floor((start+end)/2);

            int result;

            

            if(input[mid] == needle) return mid;

            else if(input[mid] < needle) {

                result = findNeedle(input, mid+1, end, needle);

                if(result == -1) {

                    return end+1;

                }

            }

            else {

                result = findNeedle(input, start, mid-1, needle);

                if(result == -1) {

                    return start;

                }

            }

        }

    }

};