给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。
样例
给出数组[1,1,1,1,2,2,2],返回 1
挑战
要求时间复杂度为O(n),空间复杂度为O(1)
class Solution {
public:
/**
* @param nums: A list of integers
* @return: The majority number
*/
int majorityNumber(vector<int> nums) {
// write your code here
//第一种方法,先排序,主元素就是nums[n/2],不过时间复杂度不是O(n)
/*
int n = nums.size();
sort(nums.begin(),nums.end());
return nums[n/2];
*/
//第二种方法 时间复杂度为O(n),空间复杂度为O(1)
//因为主元素个数至少大于等于数组元素的一般
//所以先nums[0]赋值给temp,再遍历数组,若等于temp,则n++,否则n--,当n=0时交换temp的值并把n置1。
//最后的temp就是主元素。
int n = 1;
int temp = nums[0];
for(int i = 1 ;i < nums.size();i++){
if(temp == nums[i])
n++;
if(temp != nums[i])
n--;
if(n==0){
temp = nums[i];
n = 1;
}
}
return temp;
}
};