mirror of
https://gitlab.com/game-loader/hugo.git
synced 2025-04-20 05:52:07 +08:00
leetcode update
This commit is contained in:
parent
8ed9ed06f3
commit
d4ba19406c
@ -693,3 +693,59 @@ func middleNode(head *ListNode) *ListNode {
|
|||||||
### 总结
|
### 总结
|
||||||
|
|
||||||
本题是一道经典的快慢指针的简单题目, 进一步深化了快慢指针的应用.
|
本题是一道经典的快慢指针的简单题目, 进一步深化了快慢指针的应用.
|
||||||
|
|
||||||
|
## day11 2024-03-08
|
||||||
|
|
||||||
|
### 3005. Count Elements With Maximum Frequency
|
||||||
|
|
||||||
|
You are given an array nums consisting of positive integers.
|
||||||
|
|
||||||
|
Return the total frequencies of elements in nums such that those elements all have the maximum frequency.
|
||||||
|
|
||||||
|
The frequency of an element is the number of occurrences of that element in the array.
|
||||||
|
|
||||||
|
Example 1:
|
||||||
|
|
||||||
|
> Input: nums = [1,2,2,3,1,4]
|
||||||
|
> Output: 4
|
||||||
|
> Explanation: The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array.
|
||||||
|
> So the number of elements in the array with maximum frequency is 4.
|
||||||
|
|
||||||
|
Example 2:
|
||||||
|
|
||||||
|
> Input: nums = [1,2,3,4,5]
|
||||||
|
> Output: 5
|
||||||
|
> Explanation: All elements of the array have a frequency of 1 which is the maximum.
|
||||||
|
> So the number of elements in the array with maximum frequency is 5.
|
||||||
|
|
||||||
|
### 题解
|
||||||
|
|
||||||
|
因为题目给出了正整数的范围为1-100, 因此本题可以用简单的数组来解决, 数组下标表示对应的整数, 0不做任何表示. 然后遍历数组将频率最多的元素相加即可. 可以设置一个max标志位来表示当前的最大频率, 相等则增加和, 比max大则将和重置并设max为新的最大值.
|
||||||
|
|
||||||
|
### 代码
|
||||||
|
|
||||||
|
```go
|
||||||
|
func maxFrequencyElements(nums []int) int {
|
||||||
|
frequency := make([]int, 101)
|
||||||
|
for _,value := range nums{
|
||||||
|
frequency[value]++
|
||||||
|
}
|
||||||
|
max := 0
|
||||||
|
sum := 0
|
||||||
|
for _,value := range frequency{
|
||||||
|
if value > max{
|
||||||
|
max = value
|
||||||
|
sum = max
|
||||||
|
} else if value == max{
|
||||||
|
sum += value
|
||||||
|
}else{
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sum
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 总结
|
||||||
|
|
||||||
|
本题注意考查数据范围, 在数据范围有限的情况下直接使用数组要比哈希表快得多.
|
||||||
|
Loading…
Reference in New Issue
Block a user