Find First and Last Position of Element in Sorted Array (LeetCode)

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

If target is not found in the array, return [-1, -1].

You must write an algorithm with O(log n) runtime complexity.

Examples:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Input: nums = [], target = 0
Output: [-1,-1]

Solution (Java):

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int[] ans={-1,-1};
        int start=searchPosition(nums,target,true);
        int end=searchPosition(nums,target,false);
        ans[0]=start;
        ans[1]=end;
        return ans;
    }
    int searchPosition(int[]nums, int target, boolean WantStartElement){
        int start=0, end=nums.length-1,ans=-1;
        while(start<=end){
            int mid=start+(end-start)/2;
            if(target<nums[mid])
                end=mid-1;
            else if(target>nums[mid])
                start=mid+1;
            else{
                ans=mid;
                if(WantStartElement)
                    end=mid-1;
                 else
                     start= mid+1;
            }
         }    
        return ans;
}
}

Comments

Popular posts from this blog

Final Value of Variable After Performing Operations (LeetCode)

Java Output Formatting | Hackerrank

China will fight six wars in the next 50 years!