📌  相关文章
📜  最小子数组,以使得其元素的二进制表示形式中的1的数目至少为K

📅  最后修改于: 2021-05-31 23:45:46             🧑  作者: Mango

给定一个由非负整数和整数k组成的数组arr [] 。任务是找到arr []的任何子数组的最小长度,以使如果此子数组的所有元素都以二进制表示形式并连接起来形成二进制字符串,则结果字符串的1的个数至少为ķ。如果不存在这样的子数组,则打印-1

例子:

方法:想法是使用两个变量ji并将它们分别初始化为0和1,以及一个数组count_one ,它将存储存在于该数组特定元素的二进制表示中的一个人的个数以及要存储的变量sum最高1的索引个数,并用ans来存储最小长度。现在遍历数组,如果count_one的ith或jth元素的1的个数等于k,则将1等于第i个元素的数的总和大于或等于k的更新ans最小ans和(ij)+1的取值,否则,如果它小于k,则将j增加1,以增加sum的值。

下面是该方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Finds the sub-array with maximum length
int FindSubarray(int arr[], int n, int k)
{
    // Array which stores number of ones
    // present in the binary representation
    // of ith element of the array
    int count_one[n];
  
    for (int i = 0; i < n; i++) {
        count_one[i] = __builtin_popcount(arr[i]);
    }
  
    // Sum variable to store sum of
    // number of ones
    // Initialize it as number of ones
    // present in the binary representation
    // of 0th element of the array
    int sum = count_one[0];
  
    // If there is only a single element
    if (n == 1) {
        if (count_one[0] >= k)
            return 1;
        else
            return -1;
    }
  
    // Stores the minimum length
    // of the required sub-array
    int ans = INT_MAX;
  
    int i = 1;
    int j = 0;
  
    while (i < n) {
        // If binary representation of jth
        // element of array has 1's equal to k
        if (k == count_one[j]) {
            ans = 1;
            break;
        }
  
        // If binary representation of ith
        // element of array has 1's equal to k
        else if (k == count_one[i]) {
            ans = 1;
            break;
        }
  
        // If sum of number of 1's of
        // binary representation of elements upto
        // ith element is less than k
        else if (sum + count_one[i] < k) {
            sum += count_one[i];
            i++;
        }
  
        // If sum of number of 1's of
        // binary representation of elements upto
        // ith element is greater than k
        else if (sum + count_one[i] > k) {
            ans = min(ans, (i - j) + 1);
            sum -= count_one[j];
            j++;
        }
  
        else if (sum + count_one[i] == k) {
            ans = min(ans, (i - j) + 1);
            sum += count_one[i];
            i++;
        }
    }
  
    if (ans != INT_MAX)
        return ans;
  
    else
        return -1;
}
  
// Driver code
int main()
{
    int arr[] = { 1, 2, 4, 8 };
    int n = sizeof(arr) / sizeof(int);
    int k = 2;
  
    cout << FindSubarray(arr, n, k);
  
    return 0;
}


Java
// Java implementation of the approach
class GFG
{
  
// Finds the sub-array with maximum length
static int FindSubarray(int arr[], int n, int k)
{
    // Array which stores number of ones
    // present in the binary representation
    // of ith element of the array
    int []count_one = new int[n];
  
    for (int i = 0; i < n; i++)
    {
        count_one[i] = Integer.bitCount(arr[i]);
    }
  
    // Sum variable to store sum of
    // number of ones
    // Initialize it as number of ones
    // present in the binary representation
    // of 0th element of the array
    int sum = count_one[0];
  
    // If there is only a single element
    if (n == 1) 
    {
        if (count_one[0] >= k)
            return 1;
        else
            return -1;
    }
  
    // Stores the minimum length
    // of the required sub-array
    int ans = Integer.MAX_VALUE;
  
    int i = 1;
    int j = 0;
  
    while (i < n) 
    {
        // If binary representation of jth
        // element of array has 1's equal to k
        if (k == count_one[j]) 
        {
            ans = 1;
            break;
        }
  
        // If binary representation of ith
        // element of array has 1's equal to k
        else if (k == count_one[i]) 
        {
            ans = 1;
            break;
        }
  
        // If sum of number of 1's of
        // binary representation of elements upto
        // ith element is less than k
        else if (sum + count_one[i] < k)
        {
            sum += count_one[i];
            i++;
        }
  
        // If sum of number of 1's of
        // binary representation of elements upto
        // ith element is greater than k
        else if (sum + count_one[i] > k) 
        {
            ans = Math.min(ans, (i - j) + 1);
            sum -= count_one[j];
            j++;
        }
  
        else if (sum + count_one[i] == k) 
        {
            ans = Math.min(ans, (i - j) + 1);
            sum += count_one[i];
            i++;
        }
    }
  
    if (ans != Integer.MAX_VALUE)
        return ans;
  
    else
        return -1;
}
  
// Driver code
public static void main(String[] args) 
{
    int arr[] = { 1, 2, 4, 8 };
    int n = arr.length;
    int k = 2;
  
    System.out.println(FindSubarray(arr, n, k));
}
}
  
// This code is contributed by Princi Singh


Python3
# Python3 implementation of the approach 
import sys;
  
# Finds the sub-array with maximum length 
def FindSubarray(arr, n, k) : 
  
    # Array which stores number of ones 
    # present in the binary representation 
    # of ith element of the array 
    count_one = [0] * n; 
  
    for i in range(n) : 
        count_one[i] = bin(arr[i]).count('1');
      
    # Sum variable to store sum of 
    # number of ones 
    # Initialize it as number of ones 
    # present in the binary representation 
    # of 0th element of the array 
    sum = count_one[0]; 
  
    # If there is only a single element 
    if (n == 1) :
          
        if (count_one[0] >= k) :
            return 1; 
        else :
            return -1; 
      
    # Stores the minimum length 
    # of the required sub-array 
    ans = sys.maxsize; 
  
    i = 1; 
    j = 0; 
  
    while (i < n) :
          
        # If binary representation of jth 
        # element of array has 1's equal to k 
        if (k == count_one[j]) :
            ans = 1; 
            break; 
          
        # If binary representation of ith 
        # element of array has 1's equal to k 
        elif (k == count_one[i]) :
            ans = 1;
            break; 
          
        # If sum of number of 1's of 
        # binary representation of elements upto 
        # ith element is less than k 
        elif (sum + count_one[i] < k) : 
            sum += count_one[i]; 
            i += 1; 
          
        # If sum of number of 1's of 
        # binary representation of elements upto 
        # ith element is greater than k 
        elif (sum + count_one[i] > k) : 
            ans = min(ans, (i - j) + 1); 
            sum -= count_one[j]; 
            j += 1; 
          
        elif (sum + count_one[i] == k) :
            ans = min(ans, (i - j) + 1); 
            sum += count_one[i]; 
            i += 1; 
  
    if (ans != sys.maxsize) :
        return ans; 
  
    else :
        return -1; 
  
# Driver code 
if __name__ == "__main__" :
  
    arr = [ 1, 2, 4, 8 ]; 
    n = len(arr); 
    k = 2; 
  
    print(FindSubarray(arr, n, k)); 
  
# This code is contributed by Ryuga


C#
// C# implementation of the approach
using System;
      
class GFG
{
  
// Finds the sub-array with maximum length
static int FindSubarray(int []arr, int n, int k)
{
    // Array which stores number of ones
    // present in the binary representation
    // of ith element of the array
    int []count_one = new int[n];
    int i = 0;
    for (i = 0; i < n; i++)
    {
        count_one[i] = bitCount(arr[i]);
    }
  
    // Sum variable to store sum of
    // number of ones
    // Initialize it as number of ones
    // present in the binary representation
    // of 0th element of the array
    int sum = count_one[0];
  
    // If there is only a single element
    if (n == 1) 
    {
        if (count_one[0] >= k)
            return 1;
        else
            return -1;
    }
  
    // Stores the minimum length
    // of the required sub-array
    int ans = int.MaxValue;
  
    i = 1;
    int j = 0;
  
    while (i < n) 
    {
        // If binary representation of jth
        // element of array has 1's equal to k
        if (k == count_one[j]) 
        {
            ans = 1;
            break;
        }
  
        // If binary representation of ith
        // element of array has 1's equal to k
        else if (k == count_one[i]) 
        {
            ans = 1;
            break;
        }
  
        // If sum of number of 1's of
        // binary representation of elements upto
        // ith element is less than k
        else if (sum + count_one[i] < k)
        {
            sum += count_one[i];
            i++;
        }
  
        // If sum of number of 1's of
        // binary representation of elements upto
        // ith element is greater than k
        else if (sum + count_one[i] > k) 
        {
            ans = Math.Min(ans, (i - j) + 1);
            sum -= count_one[j];
            j++;
        }
  
        else if (sum + count_one[i] == k) 
        {
            ans = Math.Min(ans, (i - j) + 1);
            sum += count_one[i];
            i++;
        }
    }
  
    if (ans != int.MaxValue)
        return ans;
  
    else
        return -1;
}
  
static int bitCount(long x)
{
    int setBits = 0;
    while (x != 0) 
    {
        x = x & (x - 1);
        setBits++;
    }
    return setBits;
}
  
// Driver code
public static void Main(String[] args) 
{
    int []arr = { 1, 2, 4, 8 };
    int n = arr.Length;
    int k = 2;
  
    Console.WriteLine(FindSubarray(arr, n, k));
}
}
  
// This code is contributed by Rajput-Ji


输出:
2

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。