leetcode169: Majority Elemen

来源:互联网 发布:淘宝的好评可以删除吗 编辑:程序博客网 时间:2024/05/22 09:38
要求:

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.

注意:要考虑数组只含有一个元素这种特殊情况。由于题目给定了出现次数大于n/2的这个数字一定存在,所以简单了很多。直接用ArrayList和HashSet将每个不同的数组元素找出来,再一一和数组进行比对,计算出现次数即可。

思考:如果是求一个数组出现次数最多的那个元素怎么办?是继续用这种办法遍历,再对出现次数排序还是改用Map?(没有进行验证)

public int isUgly(int[] nums) {if(nums.length==1)return nums[0];HashSet set = new HashSet();ArrayList list = new ArrayList();for (int i = 0; i < nums.length; i++)list.add(nums[i]);set.addAll(list);list.clear();list.addAll(set);int flag;int count=0;for(int i=0;i<list.size();i++){flag=Integer.parseInt(String.valueOf(list.get(i)));for(int j=0;j<nums.length;j++){if(flag==nums[j])count++;}if(count>nums.length/2)return flag;else    count=0;}return 0;}


0 0
原创粉丝点击