leetcode-34 在排序数组中查找元素的第一个和最后一个位置

package com.example.lettcode.dailyexercises;

/**
 * @Class SearchRange
 * @Description 34 在排序数组中查找元素的第一个和最后一个位置
 * 给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。 
 *  如果数组中不存在目标值 target,返回 [-1, -1]。 
 *
 *  示例 1: 
 * 	输入:nums = [5,7,7,8,8,10], target = 8
 * 	输出:[3,4] 
 *  示例 2: 
 * 	输入:nums = [5,7,7,8,8,10], target = 6
 * 	输出:[-1,-1] 
 *  示例 3: 
 * 	输入:nums = [], target = 0
 * 	输出:[-1,-1] 
 *
 *  提示: 
 * 	0 <= nums.length <= 105 
 * 	-109 <= nums[i] <= 109 
 * 	nums 是一个非递减数组 
 * 	-109 <= target <= 109 
 * @Author
 * @Date 2020/12/1
 **/
public class SearchRange {
    public static int[] searchRange(int[] nums, int target) {
        if (nums == null) return new int[]{-1, -1};

        int index = findIndex(nums, target, 0, nums.length-1);
        if (index == -1) return new int[]{-1, -1};

        int firstIndex = index, secondIndex = index;
        while (firstIndex >= 0) {
            if (target == nums[firstIndex]) firstIndex--;
            else break;
        }
        while (secondIndex < nums.length) {
            if (target == nums[secondIndex]) secondIndex++;
            else break;
        }
        return new int[]{++firstIndex, --secondIndex};
    }

    private static int findIndex(int[] nums, int target, int start, int end) {

        if (start > end) return -1;
        int middle = (start + end) >> 1;
        if (nums[middle] == target) return middle;
        if (nums[middle] > target)
            return findIndex(nums, target, start, middle - 1);
        return findIndex(nums, target, middle + 1, end);
    }
}
// 测试用例
public static void main(String[] args) {
	int[] nums = new int[]{5, 7, 7, 8, 8, 10};
	int target = 8;
	int[] ans = searchRange(nums, target);
	System.out.println("SearchRange demo01:" + ans[0] + "," + ans[1]);

	nums = new int[]{5, 7, 7, 8, 8, 10};
	target = 6;
	ans = searchRange(nums, target);
	System.out.println("SearchRange demo02:" + ans[0] + "," + ans[1]);

	nums = new int[]{5, 7, 7, 8, 8, 10};
	target = 5;
	ans = searchRange(nums, target);
	System.out.println("SearchRange demo03:" + ans[0] + "," + ans[1]);

	nums = new int[]{5, 7, 7, 8, 8, 10};
	target = 10;
	ans = searchRange(nums, target);
	System.out.println("SearchRange demo04:" + ans[0] + "," + ans[1]);

	nums = new int[]{};
	target = 0;
	ans = searchRange(nums, target);
	System.out.println("SearchRange demo05:" + ans[0] + "," + ans[1]);

	nums = new int[]{1};
	target = 1;
	ans = searchRange(nums, target);
	System.out.println("SearchRange demo06:" + ans[0] + "," + ans[1]);

	nums = new int[]{1,3};
	target = 1;
	ans = searchRange(nums, target);
	System.out.println("SearchRange demo06:" + ans[0] + "," + ans[1]);
}
原文地址:https://www.cnblogs.com/fyusac/p/14067147.html