給定一個整型數組,找出主元素,它在數組中的出現次數嚴格大於數組元素個數的二分之一。
注意事項
You may assume that the array is non-empty and the majority number always exist in the array.
給出數組[1,1,1,1,2,2,2],返回 1
public class Solution {
/**
* 第二種方法 時間複雜度爲O(n),空間複雜度爲O(1)
//因爲主元素個數至少大於等於數組元素的一般
//所以先nums[0]賦值給temp,再遍歷數組,若等於temp,則n++,否則n--,
當n=0時交換temp的值並把n置1。
//最後的temp就是主元素。
*/
public int majorityNumber(ArrayList<Integer> nums){
int n = 1;//計數
int temp = nums.get(0);//先賦值給date,
for(int i =1;i<nums.size();i++){//再遍歷數組
if(temp == nums.get(i)){//若等於temp,則n++,
n++;
}else{
n--;//不相同否則--
}
if(n == 0){//當n=0時交換temp的值並把n置1。
temp = nums.get(i);//
n =1;
}
}
return temp;//當n不爲0的時候的數
}
}