【LeetCode从零单排】No.169 Majority Element(hashmap用法)

简介: 题目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

题目

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.

代码

import java.util.Hashtable;
import java.util.Iterator;
public class Solution {
    public int majorityElement(int[] num) {
          Hashtable<Integer,Integer> rightList = new Hashtable<Integer,Integer>();
		   for(int i=0;i<num.length;i++)
		      {
			  if(rightList.get(num[i])==null){
				  rightList.put(num[i], 1);
			  }
			  else{
				  rightList.put(num[i], rightList.get(num[i])+1);
			  }
		     }
		   int result_value=0;
		   int result_key=0;
		   for(Iterator itr = rightList.keySet().iterator(); itr.hasNext();){
			  		   int key = (Integer) itr.next(); 
			  		   if(rightList.get(key)>result_value){
			  			  result_key=key;
			  			  result_value=rightList.get(key);			  			   
			  		   }
		   }
		   return result_key;
    }
}




/********************************

* 本文来自博客  “李博Garvin“

* 转载请标明出处:http://blog.csdn.net/buptgshengod

******************************************/



目录
相关文章
|
5月前
|
存储 索引 Python
leetcode-350:两个数组的交集 II(python中Counter的用法,海象运算符:=)
leetcode-350:两个数组的交集 II(python中Counter的用法,海象运算符:=)
52 0
|
11月前
Leetcode 230. Kth Smallest Element in a BST
先来看下二叉搜索树的性质,对于任意一个非叶子节点,它的左子树中所有的值必定小于这个节点的val,右子树中所有的值必定大于或等于当前节点的val。 这条性质就保证了如果我们对二叉搜索树做中序遍历,中序遍历的结果肯定是有序的。对于此题而言,我们只需要拿到中序遍历结果,然后返回第k个即可,时间复杂度是O(n)。
61 1
|
存储 缓存 Rust
Rust 笔记:Rust 语言中映射(HashMap)与集合(HashSet)及其用法
本文介绍 Rust 中哈希结构相关概念及其使用。在 Rust 中,提供了两种哈希表,一个是 HashMap,另外一个是 HashSet,本文都将逐一介绍,并介绍 哈希函数 的用法。
296 0
|
Python
LeetCode 378. Kth S Element in a Sorted Matrix
给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第k小的元素。 请注意,它是排序后的第k小元素,而不是第k个元素。
102 0
LeetCode 378. Kth S Element in a Sorted Matrix
|
算法
LeetCode 229. Majority Element II
给定一个大小为 n 的数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。 说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1)。
85 0
LeetCode 229. Majority Element II
|
索引
LeetCode 162. Find Peak Element
给定一个输入数组 nums,其中 nums[i] ≠ nums[i+1],找到峰值元素并返回其索引。 数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即可。
97 0
LeetCode 162. Find Peak Element
|
算法 Python
LeetCode 169. 多数元素 Majority Element
LeetCode 169. 多数元素 Majority Element
LeetCode 215. Kth Largest Element in an Array
在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
82 0
|
Java C++
LeetCode之Remove Element
LeetCode之Remove Element
105 0
LeetCode之Next Greater Element I
LeetCode之Next Greater Element I
78 0