Find First and Last Position of Element in Sorted Array

拈花ヽ惹草 提交于 2020-02-24 23:24:14

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]

思路:binary search标准模板走起;

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int[] res = {-1,-1};
        if(nums == null || nums.length == 0) {
            return res;
        }
        res[0] = findFirstPosition(nums, target, 0, nums.length - 1);
        res[1] = findLastPosition(nums, target, 0, nums.length - 1);
        return res;
    }
    
    private int findFirstPosition(int[] nums, int target, int start, int end) {
        while(start + 1 < end) {
            int mid = start + (end - start) / 2;
            if(nums[mid] >= target) {
                end = mid;
            } else {
                // nums[mid] < target;
                start = mid;
            }
        }
        
        if(nums[start] == target) {
            return start;
        } else if(nums[end] == target) {
            return end;
        } else {
            return -1;
        }
    }
    
    private int findLastPosition(int[] nums, int target, int start, int end) {
        while(start + 1 < end) {
            int mid = start + (end - start) / 2;
            if(nums[mid] <= target) {
                start = mid;
            } else {
                // nums[mid] > target;
                end = mid;
            }
        }
        
        if(nums[end] == target) {
            return end;
        } else if(nums[start] == target) {
            return start;
        } else {
            return -1;
        }
    }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!