java求解LeetCode题目,实现求解数组中的majority element

来源:互联网 发布:王珊数据库视频 编辑:程序博客网 时间:2024/05/18 16:54

原始的题目

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的数组,找到其中出现次数超过数组长度一半以上的元素输出
思路:
我采用的是hashmap的方法,其实对于java还是新手,这个题目是借鉴了python中字典的思想,在java中就可以是hashmap了,存储每一个数字和他出现的次数的键值对,随着遍历数组的进行更新值即可,下面是具体的实现:
package leetcode;import java.util.HashMap;import java.util.Map;/* * 给定一个长度为n的数组,找出majority element,所谓majority element就是出现次数大于n/2的那个数 */public class practice08 {public static void majorityElement(int num[]) {     Map<Integer, Integer> m = new HashMap<Integer, Integer>();       int len=num.length;       for(int i=0;i<len;i++){        if (m.containsKey(num[i])){       int num_value=m.get(num[i]);       m.put(num[i], num_value+1);       }else{       m.put(num[i], 1);       }       }               for (Integer key : m.keySet()) {         if (m.get(key)>len/2){               System.out.println("key= "+ key + " and value= " + m.get(key));         }          }   }  public static void main(String [] args){int [] A=new int[]{1,2,4,5,7,2,2,8,9,3,2,2,13,2,2,34,67,2,2,2,2,78,2,2,2,3};majorityElement(A);}}

结果如下:
key= 2 and value= 14


原创粉丝点击