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.
1 class Solution { 2 public: 3 int majorityElement(vector<int>& nums) { 4 if(nums.empty()) return 0; 5 if(nums.size() == 1) return nums[0]; 6 7 int current; 8 int count = 0; 9 for(int i = 0; i < nums.size(); i++){ 10 if(count == 0){ 11 current = nums[i]; 12 count = 1; 13 } 14 else{ 15 if(nums[i] == current) count++; 16 else count--; 17 } 18 } 19 return current; 20 } 21 };
Solution1:
1 int majorityElement(vector<int> &num) { 2 int len = num.size(); 3 for(int i = 0; i <= len / 2; i++){ 4 for(int j = i + 1; j < len - i; j++){ 5 if(num[j] < num[i]){ 6 int temp = num[i]; 7 num[i] = num[j]; 8 num[j] = num[i]; 9 } 10 } 11 } 12 return num[len/2]; 13 }
结果超时..参照https://leetcode.com/discuss/19151/solution-computation-space-problem-can-extended-situation解题思路,可得代码如下
Solution2:
1 class Solution { 2 public: 3 int majorityElement(vector<int> &num) { 4 int len = num.size(); 5 int count = 0; 6 int count_number = 0; 7 for(int i = 0; i < len; i++){ 8 if(count == 0){ 9 count_number = num[i]; 10 count++; 11 } 12 else{ 13 if(count_number == num[i]) count++; 14 else count--; 15 } 16 } 17 return count_number; 18 } 19 };