Topic:
Given an array of size n, find the majority element. The majority element is the element, the appears more than times ⌊ n/2 ⌋
.
Assume that the array was non-empty and the majority element always exist in the array.
Idea: You can use dictionary to record the number of occurrences of each number in the array and the number of output occurrences greater than N/2
Or, after sorting the array, the number in the middle of the array is the
Code:
Public classSolution { Public intMajorityelement (int[] nums) { intTime = Nums. Length/2; /*using Dictionary dictionary<int,int> dic = new dictionary<int,int> (); for (int i = 0;i < Nums. length;i++) {if (!dic. ContainsKey (Nums[i]) dic. ADD (nums[i],0); } for (int j = 0;j < Nums. length;j++) {if (DIC). ContainsKey (Nums[j])) {dic[nums[j]]++; if (Dic[nums[j]] > Time) return nums[j]; }} return 0; */ //sort the array, the middle number is theArray.Sort (nums); returnNums[time]; }}
[LeetCode169] Majority element to find the number of occurrences in an array greater than N/2