comments | edit_url |
---|---|
true |
统计一个数字在排序数组中出现的次数。
示例 1:
输入: nums = [5,7,7,8,8,10]
, target = 8
输出: 2
示例 2:
输入: nums = [5,7,7,8,8,10]
, target = 6
输出: 0
提示:
0 <= nums.length <= 105
-109 <= nums[i] <= 109
nums
是一个非递减数组-109 <= target <= 109
注意:本题与主站 34 题相同(仅返回值不同):https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/
由于数组 nums
已排好序,我们可以使用二分查找的方法找到数组中第一个大于等于 target
的元素的下标 target
的元素的下标 target
的个数就是
时间复杂度
class Solution:
def search(self, nums: List[int], target: int) -> int:
l = bisect_left(nums, target)
r = bisect_right(nums, target)
return r - l
class Solution {
private int[] nums;
public int search(int[] nums, int target) {
this.nums = nums;
int l = search(target);
int r = search(target + 1);
return r - l;
}
private int search(int x) {
int l = 0, r = nums.length;
while (l < r) {
int mid = (l + r) >>> 1;
if (nums[mid] >= x) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
}
class Solution {
public:
int search(vector<int>& nums, int target) {
auto l = lower_bound(nums.begin(), nums.end(), target);
auto r = upper_bound(nums.begin(), nums.end(), target);
return r - l;
}
};
func search(nums []int, target int) int {
l := sort.SearchInts(nums, target)
r := sort.SearchInts(nums, target+1)
return r - l
}
impl Solution {
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
let search = |x| {
let mut l = 0;
let mut r = nums.len();
while l < r {
let mid = l + (r - l) / 2;
if nums[mid] >= x {
r = mid;
} else {
l = mid + 1;
}
}
l as i32
};
search(target + 1) - search(target)
}
}
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function (nums, target) {
const search = x => {
let l = 0;
let r = nums.length;
while (l < r) {
const mid = (l + r) >> 1;
if (nums[mid] >= x) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
};
const l = search(target);
const r = search(target + 1);
return r - l;
};
public class Solution {
public int Search(int[] nums, int target) {
int l = search(nums, target);
int r = search(nums, target + 1);
return r - l;
}
private int search(int[] nums, int x) {
int l = 0, r = nums.Length;
while (l < r) {
int mid = (l + r) >> 1;
if (nums[mid] >= x) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
}
class Solution {
private var nums: [Int] = []
func search(_ nums: [Int], _ target: Int) -> Int {
self.nums = nums
let leftIndex = search(target)
let rightIndex = search(target + 1)
return rightIndex - leftIndex
}
private func search(_ x: Int) -> Int {
var left = 0
var right = nums.count
while left < right {
let mid = (left + right) / 2
if nums[mid] >= x {
right = mid
} else {
left = mid + 1
}
}
return left
}
}