Majority Element 找出一个数组中出现次数最多的元素
来源:互联网 发布:数据库管理dba 编辑:程序博客网 时间:2024/06/05 05:58
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.
public class Solution {
public int majorityElement(int[] nums) {
HashMap<Integer,Integer>map=new HashMap<Integer,Integer>();
int count=0;
int res=0;
for(int i=0;i<nums.length;i++){
if(map.get(nums[i])==null) map.put(nums[i],1);
else map.put(nums[i],map.get(nums[i])+1);
if(count<map.get(nums[i])) count=map.get(nums[i]);
}
for(int i=0;i<nums.length;i++){
if(map.get(nums[i])==count) res=nums[i];
}
return res; //返回语句必须放在这儿,放在上边的for语句里边会爆没有返回语句的错误
}
}
下边这个解法是参考的别人,因为有Arrays.sort()函数,所以简直是简单,因为题目说了那个出现次数比数组全长的一半还多
public class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
}
- Majority Element 找出一个数组中出现次数最多的元素
- Leetcode:169. Majority Element(找到数组中出现次数最多的元素)
- LeetCode--Majority Element(出现次数最多的元素)Python
- 找出一个列表中出现次数最多的元素
- java找出一个数组中出现次数最多的那个元素
- java找出一个数组中出现次数最多且最大的那个元素
- java找出一个数组中出现次数最多的那个元素(用HashSet很新颖)
- java找出一个数组中出现次数最多的那个元素
- 统计一个无序数组中出现次数最多的元素
- 统计一个无序数组中出现次数最多的元素
- leetcode Majority Element 寻找出现次数最多元素
- 找出一个数组中出现次数超过一半的元素
- 找出数组里面元素出现次数最多的问题
- 找出数组里面元素出现次数最多的问题
- python 找出序列中出现次数最多的元素方法。
- python 找出序列中出现次数最多的元素方法
- 一个简单的实现找出数组中一个数字出现次数最多的数字的算法
- 一个简单的算法---实现找出数组中一个数字出现次数最多的数字
- Android测试之Monkey
- 单向循环链表
- jQuery中的事件
- Linux中线程和进程的区别
- 深入分析JavaWeb Item40 -- 文件上传和下载
- Majority Element 找出一个数组中出现次数最多的元素
- ArcGIS Server:Service failed to start
- Python开发简单爬虫(二)
- CSDN blog第一文
- linux环境下实现svn服务器支持http协议
- linux中文件描述符fd和文件指针flip的理解
- HTML+CSS+javaScript 基础知识(三)
- java读取properties文件的几种方法
- [Cocoa]_[初级]_[Cocoa设计模式总结]