Java solution fairly simple


  • 0
    K

    Java Solution that divides the list by 2 searching for the number. Once it is found, we go left from the spot until we find the left index. Then go right from the spot to find the right index.

    public class Solution {
        	public int[] searchRange(int[] nums, int target) {
    		int location = findLocation(0, nums.length -1 , nums, target);
    		if(location == -1){
    			
    			return new int[]{-1,-1};
    			
    		} else {
    			return new int[] {searchLeftSide(location, nums), searchRightSide(location, nums)};
    		}
    		
    	}
    
    	public int findLocation(int start, int end, int[] nums, int target) {
    		if(end - start <=1){ \\ there can only be 2 options here, the start or the end
    			if(nums[start]==target){
    				return start;
    			} else if(nums[end]== target){
    				return end;
    			}
    		}else{
    			int mid = (end + start)/2;
    			if(nums[mid]<target) return findLocation(mid, end, nums, target);
    			if(nums[mid]>target) return findLocation(start, mid, nums, target);
    			if(nums[mid]==target) return mid;
    		}
    		return -1;
    	}
    
    	public int searchLeftSide(int index, int[] nums) {
    		if(index == 0) return index; //are there any values to the left?
    		int leftIndex = index -1;
    		if(nums[index]== nums[leftIndex]) return searchLeftSide(leftIndex, nums);
    		return index;
    	}
    
    	public int searchRightSide(int index, int[] nums) {
    		if(index == nums.length-1) return index; \\are there any values to the right??
    		int rightIndex = index +1;
    		if(nums[index]== nums[rightIndex]) return searchRightSide(rightIndex, nums);
    		return index;
    	}
    }
    

Log in to reply
 

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