标签:
题目:
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.
解法一:naive法
We can sort the array first, which takes time of nlog(n). Then scan once to find the longest consecutive substrings.
1 public class Solution { 2 public int majorityElement(int[] num) { 3 if(num.length==1){ 4 return num[0]; 5 } 6 7 Arrays.sort(num); 8 9 int prev=num[0]; 10 int count=1; 11 for(int i=1; i<num.length; i++){ 12 if(num[i] == prev){ 13 count++; 14 if(count > num.length/2) return num[i]; 15 }else{ 16 count=1; 17 prev = num[i]; 18 } 19 } 20 21 return 0; 22 } 23 }
解法二:Much Simpler
1 public int majorityElement(int[] num) { 2 if (num.length == 1) { 3 return num[0]; 4 } 5 6 Arrays.sort(num); 7 return num[num.length / 2]; 8 }
解法三:Linear Time Majority Vote Algorithm 很高级的样子
1 public int majorityElement(int[] nums) { 2 int result = 0, count = 0; 3 4 for(int i = 0; i<nums.length; i++ ) { 5 if(count == 0){ 6 result = nums[ i ]; 7 count = 1; 8 }else if(result == nums[i]){ 9 count++; 10 }else{ 11 count--; 12 } 13 } 14 15 return result; 16 }
reference:http://www.programcreek.com/2014/02/leetcode-majority-element-java/
http://www.cs.utexas.edu/~moore/best-ideas/mjrty/
标签:
原文地址:http://www.cnblogs.com/hygeia/p/4645237.html