Loading
Leetcode / 35. Search Insert Position

Pick a programming language:

Here is the source code for the solution to this problem.

public class Solution {
    // time O(log(N))
    // space O(1)
    public int SearchInsert(int[] nums, int target) {
        int i = 0;
        int j = nums.Length - 1;

        while (i <= j)
        {
            int m = (i + j + 1) / 2;
            if (nums[m] == target)
            {
                return m;
            }
            else if (nums[m] < target)
            {
                i = m + 1;
            }
            else
            {
                j = m - 1;
            }
        }

        return i;
    }

    // time O(n)
    // space O(1)
    // public int SearchInsert(int[] nums, int target) {
    //     for (int i = nums.Length - 1; i >= 0; i--)
    //     {
    //         if (target < nums[i])
    //         {
    //             continue;
    //         }
    //         else if (target == nums[i])
    //         {
    //             return i;
    //         }
    //         return i + 1;
    //     }
    //     return 0;
    // }
}
Did you like the lesson? 😆👍
Consider a donation to support our work: