LeetCode 面试题39. 数组中出现次数超过一半的数字

题目链接:https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例 1:

输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2

限制:

1 <= 数组长度 <= 50000

 1 int majorityElement(int* nums, int numsSize){
 2     int i,cnt=1,tmp=nums[0];
 3     for(i=1;i<numsSize;i++){
 4         if(nums[i]==tmp) cnt++;
 5         else cnt--;
 6         if(cnt==0){
 7             tmp=nums[i];
 8             cnt=1;
 9         }
10     }
11     return tmp;
12 }

 

posted @ 2020-03-04 00:18  wydxry  阅读(358)  评论(0编辑  收藏  举报
Live2D