169 Majority Element
2015-07-27 23:07
603 查看
题目链接:https://leetcode.com/problems/majority-element/
题目:
解题思路:
每次找出两个不同的元素删除,最后剩下的就是超过一半的元素。即:和其它元素对消后,还有剩余的元素就是多数元素。
注意:
如果题目要求是⌊ n/k ⌋,则每次找出 k 个不同的元素来消除。
方法二:自己想出的方法
解题思路:
将每一个元素看做一个键存入hashMap,对应的键值为该元素出现的次数。遍历完数组后,遍历hashMap,判断元素出现的次数是否大于n / 2。
题目:
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. Credits: Special thanks to @ts for adding this problem and creating all test cases.
解题思路:
每次找出两个不同的元素删除,最后剩下的就是超过一半的元素。即:和其它元素对消后,还有剩余的元素就是多数元素。
注意:
如果题目要求是⌊ n/k ⌋,则每次找出 k 个不同的元素来消除。
public class Solution { public int majorityElement(int[] nums) { int n = nums.length; int ret = nums[0]; int count = 1; for(int i = 1; i < n; i ++) { if(ret == nums[i]) count ++; else { count --; if(count == 0) { ret = nums[i]; count = 1; } } } return ret; } }
42 / 42 test cases passed. Status: Accepted Runtime: 432 ms
方法二:自己想出的方法
解题思路:
将每一个元素看做一个键存入hashMap,对应的键值为该元素出现的次数。遍历完数组后,遍历hashMap,判断元素出现的次数是否大于n / 2。
public class Solution { public int majorityElement(int[] nums) { int n = nums.length; HashMap<Integer, Integer> map = new HashMap(); for(int i = 0; i < n; i ++) { int k = nums[i]; if(!map.containsKey(k)) map.put(k, 1); else map.put(k, map.get(k) + 1); } int majorityE = Integer.MIN_VALUE; for(Map.Entry<Integer, Integer> m : map.entrySet()) { int times = m.getValue(); if(times > n / 2) { majorityE = m.getKey(); break; } } return majorityE; } }
42 / 42 test cases passed. Status: Accepted Runtime: 496 ms
相关文章推荐
- SELECT INTO 和 INSERT INTO SELECT 两种表复制语句
- HLSL Shader编程基础总结
- 学习ubuntu之路(一) Ubuntu下,清屏等终端常用命令
- 索引的设计原则
- mac 下android开发 eclipse中找不到设备
- HTML基本知识点总结
- hdu 2069 Coin Change (dp 母函数 )
- 编程艺术,经典!!!!!!!!!!
- 在 VS2013 中调用 ffmpeg 库函数
- hihoCoder 1077 RMQ问题再临-线段树
- Ubuntu 12.04 使用Eclipse搭建C/C++编译环境
- [黑马程序员](第31天)高新技术之反射
- Redis 的订阅和发布
- oracle简单统计查询
- poj1088 滑雪 解题报告
- 学习使用:before和:after伪元素
- codeforce Gym 100500A Poetry Challenge(博弈,暴搜)
- 落户51,开始奋斗!
- [黑马程序员](第31天)高新技术之反射---易错点
- Spring IOC装配Bean的3种方式