1、前言
题目描述2、思路
因为是有序数组,所以可以使用二分查找,找到相关数之后,然后往两边扩,这是最朴素的思路。
3、代码
class Solution {
public int search(int[] nums, int target) {
if(nums == null || nums.length == 0){
return 0;
}
int left = 0, right = nums.length - 1;
while(left <= right){
int mid = (right + left) / 2;
if(nums[mid] == target){
int size = 1, tl = mid - 1, tr = mid + 1;
while((tl >= 0 && nums[tl] == nums[mid]) || (tr < nums.length && nums[tr] == nums[mid])){
if(tl >= 0 && nums[tl] == nums[mid]){
tl--;
size++;
}
if(tr < nums.length && nums[tr] == nums[mid]){
tr++;
size++;
}
}
return size;
}else if(nums[mid] > target){
right = mid - 1;
}else{
left = mid + 1;
}
}
return 0;
}
}
网友评论