Majority Element (算法)
Posted 静静静流
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Majority Element (算法)相关的知识,希望对你有一定的参考价值。
自己写了一种方法,看了别人的解析之后觉得自己的方法好low,不高效也不明智。所以决定记录下来。
题目要求
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
相关TAG
Array Divide and Conquer Bit Manipulation
代码
1 public class Solution { 2 public int majorityElement(int[] nums) { 3 //way1:genuis 4 int major=nums[0], count = 1; 5 for(int i=1; i<nums.length;i++){ 6 if(count==0){ 7 count++; 8 major=nums[i]; 9 }else if(major==nums[i]){ 10 count++; 11 }else count--; 12 } 13 return major; 14 15 //way2:most efficient 16 int len = nums.length; 17 Arrays.sort(nums); 18 return nums[len/2]; 19 20 //way3:mine 21 //n个元素的集合,必须出现(n/2+1)次以上 22 int len = nums.length; 23 if(len==1) 24 return nums[0]; 25 Arrays.sort(nums); 26 int majorLen = (len/2)+1; 27 int pointer = 0; 28 int count = 1; 29 while(pointer<len-1){ 30 if(count>=majorLen) 31 break; 32 else{ 33 if((pointer+1<len)&&(nums[pointer]==nums[pointer+1])) 34 count++; 35 else 36 count=1; 37 pointer++; 38 } 39 } 40 return nums[pointer]; 41 } 42 }
以上是关于Majority Element (算法)的主要内容,如果未能解决你的问题,请参考以下文章