[leetcode][34] Find First and Last Position of Element in Sorted Array
Posted ekoeko
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode][34] Find First and Last Position of Element in Sorted Array相关的知识,希望对你有一定的参考价值。
34. Find First and Last Position of Element in Sorted Array
Given an array of integers nums 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].
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
解析
思路很简单,二分查找,找两次,第一次找到目标值,第二次找目标值+1,就可以定位出目标值的范围。
参考答案
自己写的:
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] res = new int[2];
if (nums.length == 0) {
res[0] = -1;
res[1] = -1;
return res;
}
int lo = binarySearch(nums, target);
if (nums[lo] != target) {
res[0] = -1;
res[1] = -1;
return res;
}
if (nums.length == 1) {
res[0] = lo;
res[1] = lo;
return res;
}
int hi = binarySearch(nums, target+1);
res[0] = lo;
res[1] = nums[hi] == target ? hi : hi-1;
return res;
}
public int binarySearch(int[] nums, int target) {
int lo = 0;
int hi = nums.length - 1;
while(lo < hi) {
int mid = (lo + hi) / 2;
if (nums[mid] < target) {
lo = mid + 1;
} else {
hi = mid;
}
}
return lo;
}
}
别人写的:
public class Solution {
public int[] searchRange(int[] A, int target) {
int start = Solution.firstGreaterEqual(A, target);
if (start == A.length || A[start] != target) {
return new int[]{-1, -1};
}
return new int[]{start, Solution.firstGreaterEqual(A, target + 1) - 1};
}
//find the first number that is greater than or equal to target.
//could return A.length if target is greater than A[A.length-1].
//actually this is the same as lower_bound in C++ STL.
private static int firstGreaterEqual(int[] A, int target) {
int low = 0, high = A.length;
while (low < high) {
int mid = low + ((high - low) >> 1);
//low <= mid < high
if (A[mid] < target) {
low = mid + 1;
} else {
//should not be mid-1 when A[mid]==target.
//could be mid even if A[mid]>target because mid<high.
high = mid;
}
}
return low;
}
}
虽然对二分法已经很熟悉了,但是在一些边界上还是了解不够,这里我去了length-1为hi,这样查找的数组上边界还要加判断,别人是取了length为hi。比如在【2,2】里面插找3,上面一种方法返回的是1,后面一种返回的是2,在【2,3】里面查找3,两种方法返回的都是1。总结下来就是,当查找的数超出上边界时,第一种方法返回右边界下标,第二种方法仍然可以返回不小于目标值的最小值。用第二种方法就不用对结果加判断了,更优雅简单.
以上是关于[leetcode][34] Find First and Last Position of Element in Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 34. Find First and Last Position of Element in Sorted Array
Leetcode 34 Find First and Last Position of Element in Sorted Array 解题思路 (python)
[二分搜索] leetcode 34 Find First and Last Position of Element in Sorted Array
19.2.2 [LeetCode 34] Find First and Last Position of Element in Sorted Array
[LeetCode] 34. Find First and Last Position of Element in Sorted Array
[Lintcode]61. Search for a Range/[Leetcode]34. Find First and Last Position of Element in Sorted Arr