169. Majority Element

网友投稿 573 2022-10-09

169. Majority Element

169. Majority Element

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.

Example 1:

Input: [3,2,3]Output: 3

Example 2:

Input: [2,2,1,1,1,2,2]Output: 2

class Solution { private Map countNums(int[] nums) { Map counts = new HashMap(); for (int num : nums) { if (!counts.containsKey(num)) { counts.put(num, 1); } else { counts.put(num, counts.get(num)+1); } } return counts; } public int majorityElement(int[] nums) { Map counts = countNums(nums); Map.Entry majorityEntry = null; for (Map.Entry entry : counts.entrySet()) { if (majorityEntry == null || entry.getValue() > majorityEntry.getValue()) { majorityEntry = entry; } } return majorityEntry.getKey(); }}

public class Solution { public int majorityElement(int[] num) { int count = 1; int max = num[0]; for(int i = 1; i < num.length;i++) { if(max == num[i]) count++; else count--; if(count <= 0) { max = num[i]; count = 1; } } if(count > 0) { return max; } return -1; }}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:168. Excel Sheet Column Title
下一篇:Seastar 高性能服务器端应用程序框架(seastar美白舱)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~