[LeetCode] 34. Find First and Last Position of Element in Sorted Array

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

Your algorithm's runtime complexity must be in the order of O(log n).

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

Example 1:

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

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

Analyse:

Solution:

class Solution {
   // [5, 7, 7, 8, 8, 10]

    func searchRange(_ nums: [Int], _ target: Int) -> [Int] {
        var startIndex = 0;
        var endIndex = nums.count - 1;
        
        while(startIndex <= endIndex) {
            let midIndex = startIndex + (endIndex - startIndex)/2;
            let startValue = nums[startIndex]; 
            let midValue = nums[midIndex]; 
            let endValue = nums[endIndex]; 
            
            if(midValue == target) {
                return self.findIndexs(nums, target, midIndex);
                break;
            }
            
            if(target > midValue) {
                startIndex = midIndex + 1;
            }
            else {
                endIndex = midIndex - 1;
            }
        }
        
        return [-1, -1];
    }
    
    func findIndexs(_ nums: [Int], _ target: Int, _ inputIndex: Int) -> [Int] {
        var result:[Int] = []
        var startIndex = inputIndex;
        var endIndex = inputIndex;
        
        while ((startIndex - 1) >= 0 && nums[startIndex - 1] == target) {  
            startIndex -= 1;
        }
        
        while ((endIndex + 1) < nums.count && nums[endIndex + 1] == target) {  
            endIndex += 1;
        }

        result.append(startIndex);
        result.append(endIndex);
        
        return result;
    }
}

Last updated