标签:lse hashtable eth sort get element new count ==
// method 1 public static int majorityElement_1(int[] num) { int major=num[0], count = 1; for (int i=1; i<num.length;i++) { if (count == 0) { count++; major=num[i]; } else if (major == num[i]) { count++; } else count--; } return major; } // method 2 public static int majorityElement_2(int[] nums) { Arrays.sort(nums); return nums[nums.length/2]; } // method 3 public static int majorityElement_3(int[] nums) { Map<Integer, Integer> myMap = new HashMap<Integer, Integer>(); //Hashtable<Integer, Integer> myMap = new Hashtable<Integer, Integer>(); int ret=0; for (int num: nums) { if (!myMap.containsKey(num)) myMap.put(num, 1); else myMap.put(num, myMap.get(num)+1); if (myMap.get(num)>nums.length/2) { ret = num; break; } } return ret; }
【LeetCode-169】找出数组中出现次数大于? n/2 ?次的数
标签:lse hashtable eth sort get element new count ==
原文地址:https://www.cnblogs.com/nachdenken/p/12737711.html