Title Source: http://www.lintcode.com/zh-cn/problem/majority-number/
This problem note test instructions, the given array must be present in this main element, cannot give an array test without the main element.
Method 1: Poor lifting method
Uses two for loops to calculate the number of occurrences of each element, and returns the element if that element occurs more than One-second of the array element.
You can accept the following procedures:
1 classSolution {2 Public:3 /**4 * @param nums:a list of integers5 * @return: The majority number6 */7 intMajoritynumber (vector<int>nums) {8 //Write your code here9 intCount=1;Ten for(intI=0; I<nums.size (); i++) One { A for(intj=0; J<nums.size (); j + +) - { - if(i!=j&&nums[i]==Nums[j]) thecount++; - } - if(Count>nums.size ()/2) - returnNums[i]; + } - return 0; + } A};
Method 2: Sorting method
Sort the array, and the middle number must be the main element. Think of a ruler, if there is a piece of something larger than its length of one-second covering it, this thing will certainly occupy the middle point of the ruler.
You can accept the following procedures:
1 classSolution {2 Public:3 /**4 * @param nums:a list of integers5 * @return: The majority number6 */7 intMajoritynumber (vector<int>nums) {8 //Write your code here9 sort (Nums.begin (), Nums.end ());Ten returnNums[nums.size ()/2]; One } A};
Method 3: Hash table
1 classSolution {2 Public:3 /**4 * @param nums:a list of integers5 * @return: The majority number6 */7 intMajoritynumber (vector<int>nums) {8 //Write your code here9unordered_map<int,int>counts;Ten for(inti =0; I < nums.size (); i++) One if(++counts[nums[i]] > nums.size ()/2) A returnNums[i]; - } -};
Method 4: Offset method
Sets a count to count, candidate initializes the first element of the array. Iterates through the array, count++ when the elements in the array are equal to the candidate , and when the elements in the array are not equal to candidate, Count--。 If the count value is less than 0, the candidate is set to the current array element. Candidate is the main element when traversing to the last element.
It can also be understood that each time you find a pair of different elements, delete them from the array until the array is empty or there is only one element. It is not difficult to prove that if there are more than half of the frequency of elements, then the last remaining in the array is the only element.
You can accept the following procedures:
1 classSolution {2 Public:3 /**4 * @param nums:a list of integers5 * @return: The majority number6 */7 intMajoritynumber (vector<int>nums) {8 //Write your code here9 intCandidate, Count =0;Ten for(inti =0; I < nums.size (); i++) { One if(Count = =0) { Acandidate =Nums[i]; -Count + +; -}Else { the if(Candidate = =Nums[i]) { -Count + +; -}Else { -Count--; + } - } + } A returncandidate; at } -};
[Easy] Main element