class Solution {
/*
case1:暴力法
*/
public int search(int[] nums, int target) {
int len = nums.length;
if(len<=0||len==1&&nums[0]!=target) return 0;
int res = 0;
for(int i=0;i<len;i++){
if(nums[i]==target){
res++;
}
}
return res;
}
}
class Solution {
/*
case2:利用双指针,夹逼求取,注意一下可能nums[]中并不包含target
*/
public int search(int[] nums, int target) {
int len = nums.length;
if(len<=0||len==1&&nums[0]!=target) return 0;
int left = 0,right = len-1;
boolean lflag = false,rflag = false;
while(left<right){
if(nums[right]>target){
right--;
}else{
lflag = true;
}
if(nums[left]<target){
left++;
}else{
rflag = true;
}
if(lflag&&rflag){
break;
}
}
return (nums[left]==target&&nums[right]==target)?right-left+1:0;
}
}
class Solution {
/*
case3:利用二分查找,时间复杂度为O(logn),空间复杂度为O(1)
*/
public int search(int[] nums, int target) {
int len = nums.length;
if(len<=0) return 0;
int left = 0,right = len-1,mid = 0;
while(left<=right){
mid = (left+right)/2;
if(nums[mid]>target){
right = mid-1;
}else if(nums[mid]<target){
left = mid+1;
}else{
break;
}
}
//mid指向的可能是target,也可能是target要插入的位置
if(nums[mid]!=target){
return 0;
}
int l = mid-1,r = mid+1;
while(l>=left&&nums[l]==nums[mid]){
l--;
}
while(r<=right&&nums[r]==nums[mid]){
r++;
}
return r-l-1;
}
}
class Solution { /* case1:暴力法 */ public int search(int[] nums, int target) { int len = nums.length; if(len<=0||len==1&&nums[0]!=target) return 0; int res = 0; for(int i=0;i<len;i++){ if(nums[i]==ta