leetcode5( 多数元素)
给定一个大小为 n
的数组 nums
,返回其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋
的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入:nums = [3,2,3] 输出:3
注意:
1.数组最大长和实际有限长
2.对数字记数可以用Map<key,value>
3.队列和HashSet,Map的函数调用
import java.util.*;
import static java.sql.Types.NULL;class Solution {public int majorityElement(int[] nums) {List<Integer> list = new ArrayList<Integer>();for(int i=0; i<nums.length; i++){if(nums[i]!=Integer.MAX_VALUE)list.add(nums[i]);else if (nums[i]==Integer.MAX_VALUE) {break;}}int listlen = list.size();Map<Integer,Integer> elements=new HashMap<>();for(int i=0;i<list.size();i++){if(elements.containsKey(list.get(i))){elements.put(list.get(i),elements.get(list.get(i))+1);}else{elements.put(list.get(i),1);}}for(Map.Entry<Integer,Integer> entry:elements.entrySet()){Integer key=entry.getKey();Integer value=entry.getValue();if(value>listlen/2){return key;}}return NULL;}public static void main(String[] args) {Scanner in = new Scanner(System.in);int nums[]=new int[50005];int n=0;for(int i=0;i<nums.length;i++){nums[i]=Integer.MAX_VALUE;}String str = in.nextLine();String[] strs = str.split(",");for(String str1 : strs){nums[n++]=Integer.parseInt(str1);}Solution solution = new Solution();solution.majorityElement(nums);}
}