Leetcode 169. Majority Element
题目链接: Majority Element
难度:Easy
题目大意:
找出整形数组中的主元素,即出现次数超过半数的元素。
思路1:
统计数组中各个元素的个数,出现次数最多的就是主元素。
代码
class Solution {
public int majorityElement(int[] nums) {
Map<Integer,Integer> map=new HashMap<>();
for(int n:nums){
map.put(n,map.getOrDefault(n,0)+1);
}
int res=0;
for(Integer key:map.keySet()){
if(map.get(key)>nums.length/2){
res=key;
break;
}
}
return res;
}
}
思路2:
分治法,分别求出左右两个区间的主元素,如果左右两个区间的主元素相同,那么该元素就是整个数组的主元素,否则比较左右区间主元素在整个数组中出现的次数,取出现次数较高的元素。
代码
class Solution {
public int majorityElement(int[] nums) {
return helper(nums,0,nums.length-1);
}
public int helper(int[] nums,int l,int r){
//求nums[l,r]的主元素
int n=nums.length;
if(l==r){
return nums[l];
}
int mid=l+(r-l)/2;
int left=helper(nums,l,mid);
int right=helper(nums,mid+1,r);
if(left==right){
return left;
}
else{
int leftCount=countRange(nums,l,r,left);
int rightCount=countRange(nums,l,r,right);
return leftCount>rightCount?left:right;
}
}
public int countRange(int[] nums,int l,int r,int target){
//求nums[l,r]中等于target的元素个数
int count=0;
for(int i=l;i<=r;i++){
if(nums[i]==target){
count++;
}
}
return count;
}
}
思路3:
摩尔投票法。将不同的数同归于尽,最后剩下的一定是主元素。
代码
class Solution {
public int majorityElement(int[] nums) {
//摩尔投票法,将不同的数同归于尽,最后剩下的一定是主元素
int candidate=0;
int count=0;
for(int n:nums){
if(count==0){
candidate=n;
}
if(n==candidate){
count++;
}
else{
count--;
}
}
return candidate;
}
}