**问题描述:
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.**
思路:我的想法是使用动规方法来解决这一问题,分治法这里就不赘述了。
例如数组[1,1,3,1,4,5]对应的辅助数组应存放的是[1,2,1,3,1,1]
下面附代码,欢迎大牛们指点:
public class Solution {
public int majorityElement(int[] nums) {
int n = nums.length;
int[] another = new int[n];
for(int i=0;i<n;i++){
boolean flag = false;
for(int j=i-1;j>=0;j--){
if(nums[i]==nums[j]){
another[i]=another[j]+1;
flag=true;
break;
}
}
if(flag==false){
another[i]=1;
}
//在这里判断,可以减少运行时间
if(another[i]>n/2){
return nums[i];
}
}
int max=0;
for(int i=0;i<another.length;i++){
if(another[max]<another[i]){
max = i;
}
}
return nums[max];
}
}