leetcode 169. Majority Element
来源:互联网 发布:sql服务器无法启动 编辑:程序博客网 时间:2024/06/06 15:45
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.
就是使用HashMap直接计数。
代码如下:
import java.util.HashMap;import java.util.Map;public class Solution { public int majorityElement(int[] nums) { Map<Integer, Integer> map=new HashMap<Integer, Integer>(); for(int i=0;i<nums.length;i++) map.put(nums[i], map.getOrDefault(nums[i], 0)+1); for (Integer key : map.keySet()) { if(map.get(key) >= (nums.length+1)/2) return key; } return 0; }}
下面是C++的做法,就是使用map做一次遍历操作
代码如下:
#include <iostream>#include <vector>#include <string>#include <map>using namespace std;class Solution{public: int majorityElement(vector<int>& nums) { map<int, int> mmp; for (int a : nums) { if (mmp.find(a) == mmp.end()) mmp[a] = 1; else mmp[a] += 1; } for (map<int, int>::iterator i = mmp.begin(); i != mmp.end(); i++) { if (i->second >= (nums.size() + 1) / 2) return i->first; } return 0; }};
阅读全文
0 0
- [LeetCode]169.Majority Element
- LeetCode 169.Majority Element
- 【LeetCode】169.Majority Element
- LeetCode 169. Majority Element
- LeetCode 169. Majority Element
- [leetcode] 169.Majority Element
- Leetcode 169. Majority Element
- 【LeetCode】169. Majority Element
- [LeetCode]169. Majority Element
- 169. Majority Element LeetCode
- LeetCode 169. Majority Element
- LeetCode 169. Majority Element
- Leetcode 169. Majority Element
- [LeetCode]169. Majority Element
- 【LeetCode】169. Majority Element
- leetcode 169. Majority Element
- leetcode 169. Majority Element
- [leetcode] 169. Majority Element
- SylixOS龙芯1C适配总结
- php与微信上传永久图文
- php预处理方式向mysql中插入多条数据
- redis常用命令
- call apply 和 bind的区别
- leetcode 169. Majority Element
- swift 网络请求
- Java 接口
- 详解浮点数的二进制表示
- 计蒜客编程之求最大子数列
- 有return的情况下try catch finally的执行顺序
- 【机器学习】信用风险评估评分卡建模方法及原理
- MySQL-MERGE存储引擎的使用测试
- 主从服务器的问题