169. Majority Element

来源:互联网 发布:淘宝荣耀旗舰店可靠吗 编辑:程序博客网 时间:2024/06/05 00:33

**问题描述:
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];    }}
0 0
原创粉丝点击