标签:
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.
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 };
标签:
原文地址:http://www.cnblogs.com/amazingzoe/p/4415582.html