My O(n) java solution


  • 0
    S
    public class Solution {
        public int[] searchRange(int[] nums, int target) {
            int count = 0; 
            int[] range = new int[2];
            boolean found = false; 
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] == target) {
                    if (count == 0) {
                        found = true; 
                        range[0] = i; 
                        count++; 
                    } else if (count > 0) {
                        range[1] = i;   
                        count++; 
                    }
                } else if (nums[i] > target) {
                    break; 
                }
            }
            if (count == 1) {
                range[1] = range[0];
            }
            if (!found) {
                range[0] = -1; 
                range[1] = -1;
            }
            return range; 
        }
    }

Log in to reply
 

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