C# O(log n) solution


  • 0
    K
    public class Solution {
        public int[] SearchRange(int[] nums, int target) {
            int first = 0;
            int last = nums.Length-1;
            int[] a = new int[2];
            int startpos = -1;
            int endpos = -1;
            //find the first index of the target value
            while (first <= last) {
                int mid = (first + last)/2;
                if (nums[mid]==target) {
                    startpos = mid;
                    last = mid-1;
                }
                else if (nums[mid]>target)
                    last = mid-1;
                else
                    first = mid+1;
            }
            //find the last index of the target value
            first = 0;
            last = nums.Length-1;        
            while (first <= last) {
                int mid = (first + last)/2;
                if (nums[mid]==target) {
                    endpos = mid;
                    first = mid+1;
                }
                else if (nums[mid]>target)
                    last = mid-1;
                else
                    first = mid+1;
            }        
            a[0]= startpos;
            a[1]= endpos;
            return a;
        }
    }
    

Log in to reply
 

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