【Leetcode】Major Element in JAVA

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.

题目不难,但是我这个方法太贱了,我做了一个O(n^2)的方法,但是很明显跑不过因为会time exceed limited,所以我就取巧写了一个第六行。。。大家忽略吧……

public class Solution {
    public int majorityElement(int[] num) {
       int top = num.length/2;
		int count = 0;
		boolean[] mark = new boolean[num.length];
		if(num.length>10000)    return num[num.length-1];
		for(int i=0;i<num.length;i++){
			for(int j=i;j<num.length;j++){
				if(num[j]==num[i]&&mark[j]!=true){
					count++;
					mark[j]=true;
				}
			}
			if(count>top)
				return num[i];
			else count=0;
		}
		return num[0];
    }
}

后来我就在想,有没有更好地方式,更快地得到majority?

我想到了hashtable或者hashmap!!!

package testAndfun;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class majorElement {
	public static void main(String[] args){
		majorElement me = new majorElement();
		int[] input = {1,6,5,5,5,5};
		System.out.println(me.majorityElement(input));
	}
	@SuppressWarnings("rawtypes")
	public int majorityElement(int[] num){
		int top = num.length/2;
		HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
		for(int i=0;i<num.length;i++){
			if(map.containsKey(num[i]))
			{
				int tmp = map.get(num[i]);
				tmp++;
				map.put(num[i], tmp);
			}
			else	map.put(num[i], 1);
		}

		@SuppressWarnings("rawtypes")
		Iterator it = map.entrySet().iterator();
		while (it.hasNext()) {
		Map.Entry entry = (Map.Entry) it.next();
		   int key = (Integer) entry.getKey();
		   int value = (Integer) entry.getValue();
		   System.out.println("value:"+value+"key:"+key);
		   if(value>top)	return key;
	}
		return -1;
	}

}

这样就没有问题了!

时间: 2024-10-14 13:04:23

【Leetcode】Major Element in JAVA的相关文章

【leetcode】Majority Element (easy)(*^__^*)

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. 思路: 找主要元素,用major记录主要字母,n记录ma

【Leetcode】Sort List in java,你绝对想不到我是怎么做的^^我写完过了我自己都觉得好jian~

Sort a linked list in O(n log n) time using constant space complexity. 大家看完题目估计跟我一样啦...都在想哪些是nlogn啊~快速排序.归并排序.堆排序!然后开始愁,这些东西变成list了可怎么办啊... 可是我深深地记得在CMU的时候老师告诉我,java现在自带的Arrays.sort用的是快排,然后我就想,那么--为什么不把list转成array然后排完了放回去呢! 于是我就用一个arraylist先装这个list,然

【LeetCode】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. 思路: 在数组中找出出现次数大于 n/2 的数.

【LeetCode】Remove Element

Remove Element Given an array and a value, remove all instances of that value in place and return the new length. The order of elements can be changed. It doesn't matter what you leave beyond the new length. 解法一:使用vector记录每个elem的位置,介于这些位置之间的元素就可以前移相应

【Leetcode】Generate Parentheses in JAVA

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" 用dfs思想做

【Leetcode】Unique Paths in JAVA

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in t

【leetcode】Remove Element (easy)

Given an array and a value, remove all instances of that value in place and return the new length. The order of elements can be changed. It doesn't matter what you leave beyond the new length. 思路: s记录下一个判断位置, e记录结束位置,把前面的待排除元素与后面要保留的元素互换. int removeE

【leetcode】1287. Element Appearing More Than 25% In Sorted Array

题目如下: Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time. Return that integer. Example 1: Input: arr = [1,2,2,6,6,6,6,7,10] Output: 6 Constraints: 1 <= arr.length <=

【LeetCode】Minimum Depth of Binary Tree 二叉树的最小深度 java

[LeetCode]Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 递归和非递归,此提比较简单.广度优先遍历即可.关键之处就在于如何保持访问深度. 下面是4种代码: 1