[LeetCode] Majority Element solution
来源:互联网 发布:铃声mac版 编辑:程序博客网 时间:2024/06/04 20:02
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.
ideas
1. use hashtable to save the number of the array,
2. then check the number of array elements.
3. If it is more than ⌊ n/2 ⌋
times, output this array element.
public class Solution { public int MajorityElement(int[] nums) { Dictionary <int, int> myDic = new Dictionary<int, int>(); int length = nums.Length; int result = 0; for(int i = 0; i < length; i++) { if(myDic.ContainsKey(nums[i])) { myDic[nums[i]]++; } else { myDic.Add(nums[i], 0); } } for(int i = 0; i < length; i++) { if(myDic[nums[i]] >= length/2) result = nums[i]; } return result; }}
0 0
- [LeetCode] Majority Element solution
- 169. Majority Element QuestionEditorial Solution
- 169. Majority Element QuestionEditorial Solution
- 【leetcode】Majority Element II,Majority element algorithm
- Leetcode: Majority Element &Majority Element II
- Leetcode Majority Element
- leetcode 169-Majority Element
- 【leetcode 哈希表】Majority Element
- LeetCode:Majority Element
- leetcode:Majority Element
- leetcode: Majority Element
- [LeetCode] Majority Element
- leetcode 153: Majority Element
- leetcode Majority Element
- LeetCode:Majority Element
- leetcode:Majority Element
- [LeetCode] Majority Element
- Leetcode-Majority Element
- 高数
- 2_SAT问题小结
- MySql 数据类型 和 JAVA的数据类型---映射
- HDOJ 1238 Substrings
- 黑马程序员_java基础学习笔记07_IO流
- [LeetCode] Majority Element solution
- zzuoj 10408: C.最少换乘 【最短路 经典题目】
- Java中的初始化顺序
- Eclipse中查看jar包中的源码
- 排它平方数
- SQL limit offset
- extern 用法总结
- Leetcode Rotate Array
- Excel操作