LeetCode 2917: Find the K-or of an Array
Problem Description
Explanation:
To solve this problem, we need to perform bitwise OR operations on the numbers in the input array nums
considering the condition of having at least k
numbers with a 1 in each bit position. We can achieve this by iterating through each bit position from right to left, and setting the bit in the result if the count of 1s in that position across all numbers is greater than or equal to k
.
- Initialize a variable
result
to 0. - Iterate through each bit position from right to left.
- For each bit position, count the number of 1s across all numbers in
nums
. - If the count is greater than or equal to
k
, set the bit inresult
. - Finally, return the
result
.
Time Complexity: O(n * 32) where n is the number of elements in the input array nums
.
Space Complexity: O(1)
:
Solutions
class Solution {
public int findKthOr(int[] nums, int k) {
int result = 0;
for (int i = 31; i >= 0; i--) {
int count = 0;
for (int num : nums) {
if (((num >> i) & 1) == 1) {
count++;
}
}
if (count >= k) {
result |= (1 << i);
}
}
return result;
}
}
Loading editor...