Leetcode34. Search for a Range

来源:互联网 发布:中国网络舆情监测中心 编辑:程序博客网 时间:2024/06/16 18:30

34. Search for a Range

一、原题

Given an array of integers 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].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].


二、题意解析与思路

题目的意思是,给定我们一个递增数组,然后给定我们一个数,要求我们找到这个数在数组中一开始出现的位置

和最后出现的位置。若不存在,则输出[-1,-1]。要求我们的时间复杂度为O(logn)。

该题是一个数组查找的问题,而且要求时间复杂度为O(logn),因此我们可以想到使用二分法因此我的思路是这样的:

1、首先使用二分法找该数的最早出现的位置。

2、获取其最开始出现的位置后,再次用获取的位置和length进行二分获取最后出现的位置。


三、代码

//寻找目标数最早出现的位置public int findLeft(int[] nums, int target, int left, int right) {//默认位置为-1int indexl = -1;while (left <= right) {        int middle = (left + right) / 2;        if (nums[middle] >= target) {        right = middle - 1;        } else {        left = middle + 1;        }        //若相等,则赋值        if (nums[middle] == target) {        indexl = middle;        }        }return indexl;}//寻找目标数最后出现的位置public int findRight(int[] nums, int target, int left, int right) {//默认位置为-1int indexr = -1;while (left <= right) {        int middle = (left + right) / 2;        if (nums[middle] <= target) {        left = middle + 1;        } else {        right = middle - 1;        }                if (nums[middle] == target) {        indexr = middle;        }        }return indexr;}public int[] searchRange(int[] nums, int target) {       int left = findLeft(nums, target, 0, nums.length - 1);       int right = findRight(nums, target, left, nums.length - 1);               int[] res = {left, right};       return res;    }


原创粉丝点击