原题链接:https://leetcode-cn.com/problems/majority-element/
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
题目描述:给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
分析:先定义出m代表出现次数最多的元素,mcount代表出现最多的次数,首先指针i从角标0开始遍历,角标j从i+1开始遍历,如果j所指的元素和i所指的元素一样,那么count+1,j继续向后走,出现i和j所指元素不一样时,退出;i继续向下一个元素遍历,最后比较count和mcount的大小,如果出现count>mcount则将count的值给mcount,返回i的值即可
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);//对nums进行排序
int count=0;
int m=0;//m代表的是出现次数最多的元素
int mcount=0;//mcount代表的是出现最多的次数
for(int i=0;i<nums.length;i++){
count=1;
for(int j=i+1;j<nums.length;j++){
if(nums[j]==nums[i]){
count++;
}else{
break;
}
}
if(count>mcount){
mcount=count;
m=nums[i];
}
}
return m;
}
}