本文主要是介绍leetcode解题方案--034--Search for a Range,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目
分析
查找给定数在数组的范围,数组已排序。
思路是 二分法查找所求范围的最左侧和最右侧,分别输出即可。
注意的是,得到左指针和右指针需要分别判定两种边界条件。
一个是左序号为0或右序号是数组最后一个,另一个是不存在返回-1
class Solution {public static int[] searchRange(int[] nums, int target) {if (nums == null || nums.length <= 0) {return new int[]{-1, -1};}int leftlow = 0;int lefthigh = nums.length - 1;int left = 0;while (lefthigh - leftlow > 1) {int mid = (lefthigh + leftlow) / 2;if (nums[mid] >= target) {lefthigh = mid;} else {leftlow = mid;}}int rightlow = 0;int righthigh = nums.length - 1;int right = 0;while (righthigh - rightlow > 1) {int mid = (righthigh + rightlow) / 2;if (nums[mid] <= target) {rightlow = mid;} else {righthigh = mid;}}if (nums[leftlow]!=target && nums[lefthigh]!=target) {return new int[]{-1,-1};}left = nums[leftlow] == target ? leftlow : lefthigh;right = nums[righthigh] == target ? righthigh : rightlow;return new int[]{left, right};}
}
这篇关于leetcode解题方案--034--Search for a Range的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!