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.
Tips:给定一个大小为n的数组,找到数组中出现次数大于n/2的数字。
思路:解法一:将数组排序后,位于n/2位置的数字就是大于半数的数字。
package easy; import java.util.Arrays; import java.util.Collections; public class L169MajorityElement { public int majorityElement(int[] nums) { int len=nums.length; int low=0; int high=len-1; int mid=low+(high-low)/2; Arrays.sort(nums); int bignum=nums[mid]; return bignum; } public static void main(String[] args) { L169MajorityElement l169 = new L169MajorityElement(); int[] nums={1,2,2,2,2,3}; int bignum=l169.majorityElement(nums); System.out.println(bignum); } }
解法二:按顺序遍历数组,第后一个数字等于前一个数字,count++.否则count--;
当count=0时,就需要更换数字。
public int majorityElement2(int[] nums) { int major=nums.length/2; int first=0;int count=1; for(int i=1;i<nums.length;i++){ if(nums[first]==nums[i]){ count++; }else{ count--; } if(count==0){ first=i; count=1; } } int count2=0; for(int i=0;i<nums.length;i++){ if(nums[first]==nums[i]){ count2++; } } return count2>=major?nums[first]:0; }