当前位置:网站首页>[sword finger offer] interview question 39: numbers that appear more than half of the time in the array
[sword finger offer] interview question 39: numbers that appear more than half of the time in the array
2022-07-27 15:51:00 【Jocelin47】
Method 2 : Record by index —— Moore voting
By recording a number times,
If the result of the current number and the next number are not equal , be times–
If it's the same times++
The last saved result is more than half of the number
class Solution {
public:
int majorityElement(vector<int>& nums) {
if( nums.size() == 0 )
return 0;
int result = nums[0];
int times = 1;
for( int i = 1; i < nums.size(); i++)
{
if( nums[i] == result )
times++;
else if( times == 0)
result = nums[i];
else
times--;
}
return result;
}
};
Method 3 : Hash table lookup
class Solution {
public:
int majorityElement(vector<int>& nums) {
if( nums.size() == 0 )
return 0;
unordered_map<int,int> record;
for( auto num : nums)
{
record[num]++;
if( record[num] > (nums.size() / 2) )
return num;
}
return 0;
}
};
边栏推荐
猜你喜欢
随机推荐
Huawei's general card identification function enables multiple card bindings with one key
Learn parquet file format
[system programming] process, thread problem summary
Spark 3.0 adaptive execution code implementation and data skew optimization
Set the position of the prompt box to move with the mouse, and solve the problem of incomplete display of the prompt box
Use double stars instead of math.pow()
$router.back(-1)
兆骑科创创业大赛策划承办机构,双创平台,项目落地对接
禁令之下,安防巨头海康与大华的应对之策!
C语言:字符串函数与内存函数
Multimap case
UDP message structure and precautions
网络设备硬核技术内幕 路由器篇 小结(下)
Spark RPC
Spark 3.0 Adaptive Execution 代码实现及数据倾斜优化
[regular expression] single character matching
【剑指offer】面试题53-Ⅰ:在排序数组中查找数字1 —— 二分查找的三个模版
JS find the maximum and minimum values in the array (math.max() method)
直接插入排序
Troubleshooting the slow startup of spark local programs







![[TensorBoard] OSError: [Errno 22] Invalid argument处理](/img/bf/c995f487607e3b307a268779ec1e94.png)

