/**
* 算法思想:
* 使用从头到尾遍历数组,使用记录一个数目永远>0的数字n,遇到
* 和数字不同的数组元素,如果和n不同,则看n的cnt是否大于0,如果大于0则将cnt--
* 否则,将数组当前位置的元素变为n,cnt为1。
*
*
*/
int majorityElement(int* nums, int numsSize){
int i;
int n = INT_MAX;
int cnt = 0;
for(i=0; i<numsSize; i++){
if(nums[i] == n){
cnt++;
}else{
if(cnt>0){
cnt--;
}else{
cnt = 1;
n = nums[i];
}
}
}
return n;
}
LeetCode-169-求众数-C语言
最新推荐文章于 2023-03-16 11:39:01 发布