1.題目描述
數組中有一個數字出現的次數超過數組長度的一半,請找出這個數字。
你可以假設數組是非空的,並且給定的數組總是存在多數元素。
示例 1:
輸入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
輸出: 2
限制:
1 <= 數組長度 <= 50000
2.問題分析
給出輸入[1,2,3,3,3],將這幾個數字寫成二進制數(整型32位,這裏只寫出後面4位)[0001, 0010, 0011, 0011, 0011]。在這4位二進制數字中。各自的最高位分別爲[0,0,0,0],則最高位出現最多的數字是二進制0。同理,高二位出現最多的二進制數字爲0,高三位出現最多的二進制數字爲1,最低位出現最多的二進制數字爲1。則4位出現最多的二進制數字拼起來爲0011,值爲3,即結果。
另外我們瞭解兩個知識點:
1.<<優先級大於^
2.^
在兩個數的二進制^的結果裏,相同得1不同得0
3.代碼實現
class Solution {
public:
int majorityElement(vector<int>& nums) {
int ans = 0;
int n = nums.size();
for(int i=0; i < 32; i++){
int cnt = 0;
for(int n: nums){
if(n & 1 << i) cnt ++;
}
if(cnt > n / 2)
ans ^= 1 << i;//<<優先級大於^
}
return ans;
}
};
3.2Java代碼
class Solution {
public int majorityElement(int[] nums) {
int ans = 0;
int n = nums.length;
for(int i=0; i < 32; i++){
int cnt = 0;
for(int m:nums){
if((m&1<<i)==1)
cnt++;
}
if(cnt > n / 2)
ans^= 1 << i;
}
return ans;
}
}