[LeetCode]34. Search for a Range

    xiaoxiao2021-03-25  140

    https://leetcode.com/problems/search-for-a-range/?tab=Description

    二分查找有重复数字的递增序列target的起止位置

    二分变种,好好记清楚!!!

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

    转载请注明原文地址: https://ju.6miu.com/read-7299.html

    最新回复(0)