Short Accepted C# O(log(n)) Solution 189ms


  • 4
    L
    public class Solution {
        public int SearchInsert(int[] nums, int target) {
            int begin = 0, end = nums.Length - 1;
            while(begin <= end)
            {
                if(begin == end)
                    break;
                if(nums[(begin+end)/2] > target)
                    end = (begin+end)/2;
                else if(nums[(begin+end)/2] < target)
                    begin = (begin+end)/2 + 1;
                else if(nums[(begin+end)/2] == target)
                    return (begin+end)/2;
            }
            if(nums[begin] >= target)
                return begin;
            if(nums[begin] < target)
                return begin + 1;
            return -1;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.