LeetCode 34 在排序数组中查找元素的第一个和最后一个位置
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 34 在排序数组中查找元素的第一个和最后一个位置
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
解決方案
class Solution {public int[] searchRange(int[] nums, int target) {int leftIdx = binarySearch(nums, target, 0, true);return new int[]{leftIdx, binarySearch(nums, target, leftIdx, false)};}public int binarySearch(int[] nums, int target, int left, boolean lower) {if (left == -1) {return -1;}int ans = -1;int right = nums.length - 1;while (left <= right) {int mid = (left + right) / 2;if (nums[mid] == target) {if (lower) {right = mid - 1;} else {left = mid + 1;}ans = mid;} else if (nums[mid] > target) {right = mid - 1;} else {left = mid + 1;}}return ans;} }總結
以上是生活随笔為你收集整理的LeetCode 34 在排序数组中查找元素的第一个和最后一个位置的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 33 搜索旋转排序数组
- 下一篇: LeetCode 36 有效的数独