📌  相关文章
📜  计算给定数组中可被3整除的对的最大串联

📅  最后修改于: 2021-05-19 19:15:40             🧑  作者: Mango

给定大小为N的数组arr [] ,任务是计算其元素的连接被3整除的对,每个数组元素最多存在一对。

例子:

天真的方法:解决此问题的最简单方法是遍历数组并生成给定数组的所有可能的对。对于每一对,检查该对中的元素的串联是否可被3整除。如果发现是正确的,则将两个元素都标记为false,以使该对中的两个元素不能出现在多个对中。

下面是幼稚方法的实现:

Java
// Java program to implement
// the above approach
import java.io.*;
import java.util.Arrays;
 
class GFG{
 
// Function to count pairs whose concatenation
// is divisible by 3 and each element can be
// present in at most one pair
public static int countDivBy3InArray(int[] arr)
{
     
    // Stores count pairs whose concatenation
    // is divisible by 3 and each element can
    // be present in at most one pair
    int ans = 0;
     
    // Check if an element present
    // in any pair or not
    boolean[] taken = new boolean[arr.length];
    Arrays.fill(taken, false);
     
    // Generate all possible pairs
    for(int i = 0; i < arr.length; i++)
    {
         
        // If the element already
        // present in a pair
        if (taken[i] == true)
        {
            continue;
        }
        for(int j = i + 1; j < arr.length; j++)
        {
             
            // If the element already
            // present in a pair
            if (taken[j] == true)
            {
                continue;
            }
             
            // If concatenation of elements
            // is divisible by 3
            if (Integer.parseInt(
                    Integer.toString(arr[i]) +
                    Integer.toString(arr[j])) % 3 == 0 ||
                Integer.parseInt(
                    Integer.toString(arr[j]) +
                    Integer.toString(arr[i])) % 3 == 0)
            {
                 
                // Update ans
                ans += 1;
                 
                // Mark i is True
                taken[i] = true;
                 
                // Mark j is True
                taken[j] = true;
            }
        }
    }
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
    int[] arr = { 5, 3, 2, 8, 7 };
     
    // To display the result
    System.out.println(countDivBy3InArray(arr));
}
}
 
// This code is contributed by aditya7409


Python3
# Python3 program to implement
# the above approach
 
 
# Function to count pairs whose concatenation is
# divisible by 3 and each element can be present
# in at most one pair
def countDivBy3InArray(arr):
     
     
    # Stores count pairs whose concatenation is
    # divisible by 3 and each element can be present
    # in at most one pair
    ans = 0
     
     
    # Check if an element present
    # in any pair or not
    taken = [False] * len(arr)
 
    # Generate all possible pairs
    for i in range(len(arr)):
         
         
        # If the element already
        # present in a pair
        if taken[i]:
            continue
         
        for j in range(i + 1, len(arr)):
             
             
            # If the element already
            # present in a pair
            if taken[j]:
                continue
             
             
            # If concatenation of elements
            # is divisible by 3
            if (not int(str(arr[i])+str(arr[j])) % 3 or
                 not int(str(arr[j])+str(arr[i])) % 3):
                      
                      
                # Update ans    
                ans += 1
                 
                 
                # Mark i is True
                taken[i] = True
                 
                 
                # Mark j is True
                taken[j] = True
    return ans
 
 
 
# Driver Code
arr = [5, 3, 2, 8, 7]
 
 
# To display the result
print(countDivBy3InArray(arr))


C#
// C# program to implement
// the above approach
using System;
public class GFG
{
 
  // Function to count pairs whose concatenation
  // is divisible by 3 and each element can be
  // present in at most one pair
  public static int countDivBy3InArray(int[] arr)
  {
 
    // Stores count pairs whose concatenation
    // is divisible by 3 and each element can
    // be present in at most one pair
    int ans = 0;
 
    // Check if an element present
    // in any pair or not
    bool[] taken = new bool[arr.Length];
 
    // Generate all possible pairs
    for(int i = 0; i < arr.Length; i++)
    {
 
      // If the element already
      // present in a pair
      if (taken[i] == true)
      {
        continue;
      }
      for(int j = i + 1; j < arr.Length; j++)
      {
 
        // If the element already
        // present in a pair
        if (taken[j] == true)
        {
          continue;
        }
 
        // If concatenation of elements
        // is divisible by 3
        if (Int32.Parse(
          (arr[i]).ToString() +
          (arr[j]).ToString()) % 3 == 0 ||
            Int32.Parse(
              (arr[j]).ToString() +
              (arr[i]).ToString()) % 3 == 0)
        {
 
          // Update ans
          ans += 1;
 
          // Mark i is True
          taken[i] = true;
 
          // Mark j is True
          taken[j] = true;
        }
      }
    }
    return ans;
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    int[] arr = { 5, 3, 2, 8, 7 };
 
    // To display the result
    Console.WriteLine(countDivBy3InArray(arr));
  }
}
 
// This code is contributed by 29AjayKumar


Java
// Java program to implement
// the above approach
public class GFG
{
   
  // Function to count pairs whose concatenation is
  // divisible by 3 and each element can be present
  // in at most one pair
  static int countDiv(int[] arr)
  {
 
    // Stores count of array elements whose
    // remainder is 0 by taking modulo by 3
    int rem0 = 0;
 
    // Stores count of array elements whose
    // remainder is 1 by taking modulo by 3
    int rem1 = 0;
 
    // Stores count of array elements whose
    // remainder is 2 by taking modulo by 3
    int rem2 = 0;
 
    // Traverse the array
    for(int i : arr)
    {
 
      // Stores sum of digits
      // of arr[i]
      int digitSum = 0;
 
      // Update digitSum
      digitSum += i;
 
      // If remainder of digitSum by
      // by taking modulo 3 is 0
      if(digitSum % 3 == 0)
      {
 
        // Update rem0
        rem0 += 1;
      }
 
      // If remainder of digitSum by
      // by taking modulo 3 is 1
      else if(digitSum % 3 == 1)
      {
 
        // Update rem1
        rem1 += 1;
      }
      else
      {
 
        // Update rem2
        rem2 += 1;
      }
    }
 
    return (rem0 / 2 + Math.min(rem1, rem2));
  }
 
  // Driver code
  public static void main(String[] args) {
    int[] arr = {5, 3, 2, 8, 7};
 
    // To display the result
    System.out.println(countDiv(arr));
  }
}
 
// This code is contributed by divyesh072019.


Python3
# Python3 program to implement
# the above approach
 
 
# Function to count pairs whose concatenation is
# divisible by 3 and each element can be present
# in at most one pair
def countDiv(arr):
     
     
    # Stores count of array elements whose
    # remainder is 0 by taking modulo by 3
    rem0 = 0
     
    # Stores count of array elements whose
    # remainder is 1 by taking modulo by 3
    rem1 = 0
     
     
    # Stores count of array elements whose
    # remainder is 2 by taking modulo by 3
    rem2 = 0
     
    # Traverse the array
    for i in arr:
         
       # Stores sum of digits
       # of arr[i]
        digitSum = 0
         
        for digit in str(i):
             
            # Update digitSum
            digitSum += int(digit)
         
        # If remainder of digitSum by
        # by taking modulo 3 is 0
        if digitSum % 3 == 0:
             
            # Update rem0
            rem0 += 1
             
        # If remainder of digitSum by
        # by taking modulo 3 is 1
        elif digitSum % 3 == 1:
             
            # Update rem1
            rem1 += 1
        else:
             
            # Update rem2
            rem2 += 1
             
             
    return (rem0 // 2 + min(rem1, rem2))
 
 
# Driver Code
arr = [5, 3, 2, 8, 7]
 
 
# To display the result
print(countDiv(arr))


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG {
 
  // Function to count pairs whose concatenation is
  // divisible by 3 and each element can be present
  // in at most one pair
  static int countDiv(int[] arr)
  {
     
    // Stores count of array elements whose
    // remainder is 0 by taking modulo by 3
    int rem0 = 0;
 
    // Stores count of array elements whose
    // remainder is 1 by taking modulo by 3
    int rem1 = 0;
 
    // Stores count of array elements whose
    // remainder is 2 by taking modulo by 3
    int rem2 = 0;
 
    // Traverse the array
    foreach(int i in arr)
    {
       
      // Stores sum of digits
      // of arr[i]
      int digitSum = 0;
 
      // Update digitSum
      digitSum += i;
 
      // If remainder of digitSum by
      // by taking modulo 3 is 0
      if(digitSum % 3 == 0)
      {
         
        // Update rem0
        rem0 += 1;
      }
 
      // If remainder of digitSum by
      // by taking modulo 3 is 1
      else if(digitSum % 3 == 1)
      {
         
        // Update rem1
        rem1 += 1;
      }
      else
      {
         
        // Update rem2
        rem2 += 1;
      }
    }
 
    return (rem0 / 2 + Math.Min(rem1, rem2));
  }
 
  // Driver code
  static void Main() {
    int[] arr = {5, 3, 2, 8, 7};
 
 
    // To display the result
    Console.Write(countDiv(arr));
  }
}
 
// This code is contributed by divyeshrabadiya07.


Javascript


输出:
1

时间复杂度: O(N 2 )
辅助空间: O(N)

高效方法:可以使用检查数字是否可以被3整除的概念来优化上述方法。请按照以下步骤解决问题:

  • 初始化三个变量,说rem0,REM1REM2,存储阵列元件,其余数是0,12分别当除以3的计数。
  • 遍历数组并检查以下条件:
    • 如果arr [i]%3 == 0 ,则更新cnt0 + = 1
    • 如果arr [i]%3 == 1 ,则更新cnt1 + = 1
    • 如果arr [i]%3 == 2 ,则更新cnt2 + = 1
  • 最后,打印对数,即(rem0 / 2 + min(rem1,rem2))

下面是上述方法的实现:

Java

// Java program to implement
// the above approach
public class GFG
{
   
  // Function to count pairs whose concatenation is
  // divisible by 3 and each element can be present
  // in at most one pair
  static int countDiv(int[] arr)
  {
 
    // Stores count of array elements whose
    // remainder is 0 by taking modulo by 3
    int rem0 = 0;
 
    // Stores count of array elements whose
    // remainder is 1 by taking modulo by 3
    int rem1 = 0;
 
    // Stores count of array elements whose
    // remainder is 2 by taking modulo by 3
    int rem2 = 0;
 
    // Traverse the array
    for(int i : arr)
    {
 
      // Stores sum of digits
      // of arr[i]
      int digitSum = 0;
 
      // Update digitSum
      digitSum += i;
 
      // If remainder of digitSum by
      // by taking modulo 3 is 0
      if(digitSum % 3 == 0)
      {
 
        // Update rem0
        rem0 += 1;
      }
 
      // If remainder of digitSum by
      // by taking modulo 3 is 1
      else if(digitSum % 3 == 1)
      {
 
        // Update rem1
        rem1 += 1;
      }
      else
      {
 
        // Update rem2
        rem2 += 1;
      }
    }
 
    return (rem0 / 2 + Math.min(rem1, rem2));
  }
 
  // Driver code
  public static void main(String[] args) {
    int[] arr = {5, 3, 2, 8, 7};
 
    // To display the result
    System.out.println(countDiv(arr));
  }
}
 
// This code is contributed by divyesh072019.

Python3

# Python3 program to implement
# the above approach
 
 
# Function to count pairs whose concatenation is
# divisible by 3 and each element can be present
# in at most one pair
def countDiv(arr):
     
     
    # Stores count of array elements whose
    # remainder is 0 by taking modulo by 3
    rem0 = 0
     
    # Stores count of array elements whose
    # remainder is 1 by taking modulo by 3
    rem1 = 0
     
     
    # Stores count of array elements whose
    # remainder is 2 by taking modulo by 3
    rem2 = 0
     
    # Traverse the array
    for i in arr:
         
       # Stores sum of digits
       # of arr[i]
        digitSum = 0
         
        for digit in str(i):
             
            # Update digitSum
            digitSum += int(digit)
         
        # If remainder of digitSum by
        # by taking modulo 3 is 0
        if digitSum % 3 == 0:
             
            # Update rem0
            rem0 += 1
             
        # If remainder of digitSum by
        # by taking modulo 3 is 1
        elif digitSum % 3 == 1:
             
            # Update rem1
            rem1 += 1
        else:
             
            # Update rem2
            rem2 += 1
             
             
    return (rem0 // 2 + min(rem1, rem2))
 
 
# Driver Code
arr = [5, 3, 2, 8, 7]
 
 
# To display the result
print(countDiv(arr))

C#

// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG {
 
  // Function to count pairs whose concatenation is
  // divisible by 3 and each element can be present
  // in at most one pair
  static int countDiv(int[] arr)
  {
     
    // Stores count of array elements whose
    // remainder is 0 by taking modulo by 3
    int rem0 = 0;
 
    // Stores count of array elements whose
    // remainder is 1 by taking modulo by 3
    int rem1 = 0;
 
    // Stores count of array elements whose
    // remainder is 2 by taking modulo by 3
    int rem2 = 0;
 
    // Traverse the array
    foreach(int i in arr)
    {
       
      // Stores sum of digits
      // of arr[i]
      int digitSum = 0;
 
      // Update digitSum
      digitSum += i;
 
      // If remainder of digitSum by
      // by taking modulo 3 is 0
      if(digitSum % 3 == 0)
      {
         
        // Update rem0
        rem0 += 1;
      }
 
      // If remainder of digitSum by
      // by taking modulo 3 is 1
      else if(digitSum % 3 == 1)
      {
         
        // Update rem1
        rem1 += 1;
      }
      else
      {
         
        // Update rem2
        rem2 += 1;
      }
    }
 
    return (rem0 / 2 + Math.Min(rem1, rem2));
  }
 
  // Driver code
  static void Main() {
    int[] arr = {5, 3, 2, 8, 7};
 
 
    // To display the result
    Console.Write(countDiv(arr));
  }
}
 
// This code is contributed by divyeshrabadiya07.

Java脚本


输出:
1

时间复杂度: O(N)
辅助空间: O()