class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while(left <= right){
int mid = left + (right - left) / 2;
if(nums[mid] > target){
right = mid - 1;
}else if(nums[mid] < target){
left = mid + 1;
}else{
return mid;
}
}
return -1;
}
}
Leetcode 34.在排序数组中查找元素的第⼀个和最后⼀个位置
题目
思路
通过二分查找的方式,找到这段区间的左边界和右边界即可
代码
java复制代码
class Solution {
public int[] searchRange(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int[] ret = {-1,-1};
if(nums.length == 0){
return ret;
}
//查找左边界
while(left < right){
int mid = left + (right - left) / 2;
if(nums[mid] < target){
left = mid + 1;
}else{
right = mid;
}
}
if(nums[left] != target){
return ret;
}
ret[0] = left;
left = 0;
right = nums.length - 1;
//查找右边界
while(left < right){
int mid = left + (right - left + 1) / 2;
if(nums[mid] <= target){
left = mid;
}else{
right = mid - 1;
}
}
ret[1] = right;
return ret;
}
}
class Solution {
public int searchInsert(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while(left < right){
int mid = left + (right - left)/2;
if(nums[mid] < target){
left = mid + 1;
}else{
right = mid;
}
}
if(nums[right] < target){
return right + 1;
}
return left;
}
}
class Solution {
public int peakIndexInMountainArray(int[] arr) {
int left = 0;
int right = arr.length - 1;
while(left < right){
int mid = left + (right - left) / 2;
if(arr[mid+1] > arr[mid] ){
left = mid + 1;
}else{
right = mid;
}
}
return right;
}
}
class Solution {
public int findPeakElement(int[] nums) {
int left = 0;
int right = nums.length - 1;
while(left < right){
int mid = left + (right - left)/2;
if(nums[mid+1] > nums[mid]){
left = mid + 1;
}else{
right = mid;
}
}
return right;
}
}
class Solution {
public int findMin(int[] nums) {
int left = 0;
int right = nums.length - 1;
while(left < right){
int mid = left + (right - left) / 2;
if(nums[mid] > nums[right]){
left = mid + 1;
}else{
right = mid;
}
}
return nums[left];
}
}