题解 | 数组中出现次数超过一半的数字

数组中出现次数超过一半的数字

https://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param numbers int整型vector 
     * @return int整型
     */
    int MoreThanHalfNum_Solution(vector<int>& numbers) {
    //target超过一半《==》others之和少于一半
    //移项得等价条件no of target-no of others>0
    //==》selected +1,others-1,从开头遍历换selected,最后留下来的selected就是target
    if(numbers.empty())return 0;
    int selected = numbers[0]; 
    int count=1;
    for(size_t i=1;i<numbers.size();i++)
    {
        if(count==0)
        {
            selected=numbers[i];
            count=1;
            
        }else if(numbers[i]==selected) 
        {
            count++;
        }else {
            count--;
        }
    }
    return selected;
    }
};

全部评论

相关推荐

牛客90772103...:格林美(无锡)
点赞 评论 收藏
分享
Gaynes:查看图片
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务