某班级考试成绩按非严格递增顺序记录于整数数组 scores
,请返回目标成绩 target
的出现次数。
示例 1:
输入: scores = [2, 2, 3, 4, 4, 4, 5, 6, 6, 8], target = 4 输出: 3
示例 2:
输入: scores = [1, 2, 3, 5, 7, 9], target = 6 输出: 0
提示:
0 <= scores.length <= 105
-109 <= scores[i] <= 109
scores
是一个非递减数组-109 <= target <= 109
-
public class Solution { public int CountTarget(int[] scores, int target) { int count = 0; for(int i = 0; i<scores.Length;i++){ if(scores[i] == target) count++; else if(count!=0) break; } return count; } }
public class Solution { public int CountTarget(int[] scores, int target) { int len = scores.Length; if(len == 0) return 0; int leftIndex = CountLeft(scores,target); int rightIndex = CountRight(scores,target); return rightIndex - leftIndex; } public int CountLeft(int[] scores, int target){ int left = 0,right = scores.Length; int mid = left + (right - left) / 2; while(right>left){ if(scores[mid] >= target) right = mid; else left = mid + 1; mid = left + (right - left) / 2; } return left; } public int CountRight(int[] scores, int target){ int left = 0,right = scores.Length; int mid = left + (right - left) / 2; while(right>left){ if(scores[mid] <= target) left = mid + 1; else right = mid; mid = left + (right - left) / 2; } return left; } }
public class Solution { public int CountTarget(int[] scores, int target) { int len = scores.Length; if(len == 0) return 0; int leftIndex = Count(scores,target,true); int rightIndex = Count(scores,target,false); return rightIndex - leftIndex; } public int Count(int[] scores, int target,bool isb){ int left = 0,right = scores.Length; int mid = left + (right - left) / 2; while(right>left){ if(scores[mid] > target) right = mid; else if(scores[mid] < target) left = mid + 1; else{ if(isb) right = mid; else left = mid + 1; } mid = left + (right - left) / 2; } return left; } }