Processing math: 100%

Leetcode 2917 - Find the K-or of an Array

題目

Problem#

給你一個整數陣列 nums 和整數 kK-or 代表每個 =1 的第 i 個 bit 的數量有大於等於 k 個的話,將第 i 個 bit 的數值(2i)計入總和,
題目要你回傳 K-or

測資限制#

  • 1n50
  • 1kn
  • 0val<231

想法#

檢查每個 bit 在每個數字的出現次數是否有 k 有的話計入總和

AC Code#

Copy
class Solution {
public:
int findKOr(vector<int>& nums, int k)
{
int ans = 0;
for(int i = 0; i < 32; i++)
{
int cnt = 0;
for(int j : nums)
{
if(j & (1<<i))
cnt++;
}
if(cnt >= k)
ans += pow(2, i);
}
return ans;
}
};
view raw leetcode/2917.cpp delivered with ❤ by emgithub
  • 時間複雜度: O(n)
  • 空間複雜度: O(1)