📌  相关文章
📜  检查所有子数组是否至少包含一个唯一元素

📅  最后修改于: 2021-04-22 07:45:14             🧑  作者: Mango

给定一个由N个整数组成的数组arr [] ,任务是检查数组的所有子数组中是否至少有一个唯一元素。如果发现是真的,则打印“是” 。否则,打印“否”

例子:

天真的方法:最简单的方法 是生成所有子数组,并对每个子数组使用HashMap来存储 该子数组每个元素的频率。如果任何子数组没有至少一个唯一元素,则打印“ No” 。否则,打印“是”

下面是上述方法的实现:

C++
// C++ program for above approach
#include
using namespace std;
 
// Function to check if all subarrays
// of array have at least one unique element
string check(int arr[], int n)
{
     
    // Stores frequency of subarray
    // elements
    map hm;
     
    // Generate all subarrays
    for(int i = 0; i < n; i++)
    {
         
        // Insert first element in map
        hm[arr[i]] = 1;
         
        for(int j = i + 1; j < n; j++)
        {
             
            // Update frequency of current
            // subarray in the HashMap
            hm[arr[j]]++;
 
            bool flag = false;
 
            // Check if at least one element
            // occurs once in current subarray
            for(auto x : hm)
            {
                if (x.second == 1)
                {
                    flag = true;
                    break;
                }
            }
 
            // If any subarray doesn't
            // have unique element
            if (!flag)
                return "No";
        }
 
        // Clear map for next subarray
        hm.clear();
    }
 
    // Return Yes if all subarray
    // having at least 1 unique element
    return "Yes";
}
 
// Driver Code
int main()
{
     
    // Given array arr[]
    int arr[] = { 1, 2, 1 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << check(arr, N);
}
 
// This code is contributed by bgangwar59


Java
// Java program for above approach
 
import java.util.*;
import java.lang.*;
 
class GFG {
 
    // Function to check if all subarrays
    // of array have at least one unique element
    static String check(int arr[], int n)
    {
        // Stores frequency of subarray
        // elements
        Map hm
            = new HashMap<>();
 
        // Generate all subarrays
        for (int i = 0; i < n; i++) {
 
            // Insert first element in map
            hm.put(arr[i], 1);
 
            for (int j = i + 1; j < n; j++) {
 
                // Update frequency of current
                // subarray in the HashMap
                hm.put(
                    arr[j],
                    hm.getOrDefault(arr[j], 0) + 1);
 
                boolean flag = false;
 
                // Check if at least one element
                // occurs once in current subarray
                for (Integer k : hm.values()) {
                    if (k == 1) {
                        flag = true;
                        break;
                    }
                }
 
                // If any subarray doesn't
                // have unique element
                if (!flag)
                    return "No";
            }
 
            // Clear map for next subarray
            hm.clear();
        }
 
        // Return Yes if all subarray
        // having at least 1 unique element
        return "Yes";
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given array arr[]
        int[] arr = { 1, 2, 1 };
 
        int N = arr.length;
 
        // Function Call
        System.out.println(check(arr, N));
    }
}


Python3
# Python3 program for
# the above approach
from collections import defaultdict
 
# Function to check if
# all subarrays of array
# have at least one unique
# element
def check(arr, n):
 
    # Stores frequency of
    # subarray elements
    hm = defaultdict (int)
 
    # Generate all subarrays
    for i in range(n):
 
        # Insert first element
        # in map
        hm[arr[i]] += 1
 
        for j in range(i + 1, n):
             
            # Update frequency of
            # current subarray in
            # the HashMap
            hm[arr[j]] += 1
 
            flag = False
 
            # Check if at least one
            # element occurs once in
            # current subarray
            for k in hm.values():
                if (k == 1):
                    flag = True
                    break
                
            # If any subarray doesn't
            # have unique element
            if (not flag):
               return "No"
 
        # Clear map for next
        # subarray
        hm.clear()
 
    # Return Yes if all
    # subarray having at
    # least 1 unique element
    return "Yes"
 
# Driver Code
if __name__ == "__main__":
   
    # Given array arr[]
    arr = [1, 2, 1]
 
    N = len(arr)
 
    # Function Call
    print(check(arr, N))
 
# This code is contributed by Chitranayal


C#
// C# program for the
// above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to check if all
// subarrays of array have at
// least one unique element
static String check(int []arr,
                    int n)
{
  // Stores frequency of
  // subarray elements
  Dictionary hm =
             new Dictionary();
 
  // Generate all subarrays
  for (int i = 0; i < n; i++)
  {
    // Insert first element
    // in map
    hm.Add(arr[i], 1);
 
    for (int j = i + 1; j < n; j++)
    {
      // Update frequency of current
      // subarray in the Dictionary
      if(hm.ContainsKey(arr[j]))
        hm[arr[j]]++;
      else
        hm.Add(arr[j], 1);
 
      bool flag = false;
 
      // Check if at least one 
      // element occurs once
      // in current subarray
      foreach (int k in hm.Values)
      {
        if (k == 1)
        {
          flag = true;
          break;
        }
      }
 
      // If any subarray doesn't
      // have unique element
      if (!flag)
        return "No";
    }
 
    // Clear map for next
    // subarray
    hm.Clear();
  }
 
  // Return Yes if all subarray
  // having at least 1 unique
  // element
  return "Yes";
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given array []arr
  int[] arr = {1, 2, 1};
 
  int N = arr.Length;
 
  // Function Call
  Console.WriteLine(check(arr, N));
}
}
 
// This code is contributed by Rajput-Ji


C++
// C++ program for the above approach
#include
using namespace std;
 
// Function to check if all subarrays
// have at least one unique element
string check(int arr[], int n)
{
     
    // Generate all subarray
    for(int i = 0; i < n; i++)
    {
         
        // Store frequency of
        // subarray's elements
        map hm;
         
        int count = 0;
 
        // Traverse the array over
        // the range [i, N]
        for(int j = i; j < n; j++)
        {
             
            // Update frequency of
            // current subarray in map
            hm[arr[j]]++;
 
            // Increment count
            if (hm[arr[j]] == 1)
                count++;
 
            // Decrement count
            if (hm[arr[j]] == 2)
                count--;
 
            if (count == 0)
                return "No";
        }
    }
 
    // If all subarrays have at
    // least 1 unique element
    return "Yes";
}
 
// Driver Code
int main()
{
     
    // Given array arr[]
    int arr[] = { 1, 2, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << check(arr, N);
}
 
// This code is contributed by SURENDRA_GANGWAR


Java
// Java program for the above approach
 
import java.util.*;
import java.lang.*;
 
class GFG {
 
    // Function to check if all subarrays
    // have at least one unique element
    static String check(int arr[], int n)
    {
        // Generate all subarray
        for (int i = 0; i < n; i++) {
 
            // Store frequency of
            // subarray's elements
            Map hm
                = new HashMap<>();
 
            int count = 0;
 
            // Traverse the array over
            // the range [i, N]
            for (int j = i; j < n; j++) {
 
                // Update frequency of
                // current subarray in map
                hm.put(arr[j],
                       hm.getOrDefault(arr[j], 0) + 1);
 
                // Increment count
                if (hm.get(arr[j]) == 1)
                    count++;
 
                // Decrement count
                if (hm.get(arr[j]) == 2)
                    count--;
 
                if (count == 0)
                    return "No";
            }
        }
 
        // If all subarrays have at
        // least 1 unique element
        return "Yes";
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given array arr[]
        int[] arr = { 1, 2, 1 };
        int N = arr.length;
 
        // Function Call
        System.out.println(check(arr, N));
    }
}


Python3
# Python3 program for the above approach
 
# Function to check if all subarrays
# have at least one unique element
def check(arr, n):
     
    # Generate all subarray
    for i in range(n):
         
        # Store frequency of
        # subarray's elements
        hm = {}
 
        count = 0
 
        # Traverse the array over
        # the range [i, N]
        for j in range(i, n):
             
            # Update frequency of
            # current subarray in map
            hm[arr[j]] = hm.get(arr[j], 0) + 1
 
            # Increment count
            if (hm[arr[j]] == 1):
                count += 1
 
            # Decrement count
            if (hm[arr[j]] == 2):
                count -= 1
 
            if (count == 0):
                return "No"
 
    # If all subarrays have at
    # least 1 unique element
    return "Yes"
 
# Driver Code
if __name__ == '__main__':
     
    # Given array arr[]
    arr = [ 1, 2, 1 ]
    N = len(arr)
 
    # Function Call
    print(check(arr, N))
 
# This code is contributed by mohit kumar 29


C#
// C# program for the
// above approach
using System;
using System.Collections.Generic;
class GFG {
 
// Function to check if all
// subarrays have at least
// one unique element
static String check(int []arr,
                    int n)
{
  // Generate all subarray
  for (int i = 0; i < n; i++)
  {
    // Store frequency of
    // subarray's elements
    Dictionary hm =
               new Dictionary();
    int count = 0;
 
    // Traverse the array over
    // the range [i, N]
    for (int j = i; j < n; j++)
    {
      // Update frequency of
      // current subarray in map
      if(hm.ContainsKey((arr[j])))
        hm[arr[j]]++;
      else
        hm.Add(arr[j], 1);
 
      // Increment count
      if (hm[arr[j]] == 1)
        count++;
 
      // Decrement count
      if (hm[arr[j]] == 2)
        count--;
 
      if (count == 0)
        return "No";
    }
  }
 
  // If all subarrays have at
  // least 1 unique element
  return "Yes";
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given array []arr
  int[] arr = {1, 2, 1};
  int N = arr.Length;
 
  // Function Call
  Console.WriteLine(check(arr, N));
}
}
 
// This code is contributed by gauravrajput1


输出
Yes



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

高效方法:请按照以下步骤优化上述方法:

  • [0,N – 1]范围内循环循环并创建 一个映射,用于存储当前子数组中每个字符的出现频率。
  • 创建一个变量计数以检查子数组是否至少有一个频率为1的元素。
  • 遍历数组arr []并更新映射中每个元素的频率,并将计数更新为:
    • 如果element的频率为1,则增加计数
    • 如果元素的频率为2,则递减计数
  • 在上述步骤中,如果count的值为0 ,则打印“ No” ,因为存在一个其中没有任何唯一元素的子数组。
  • 在所有迭代之后,如果count的值始终为正,则打印“ Yes”

下面是上述方法的实现:

C++

// C++ program for the above approach
#include
using namespace std;
 
// Function to check if all subarrays
// have at least one unique element
string check(int arr[], int n)
{
     
    // Generate all subarray
    for(int i = 0; i < n; i++)
    {
         
        // Store frequency of
        // subarray's elements
        map hm;
         
        int count = 0;
 
        // Traverse the array over
        // the range [i, N]
        for(int j = i; j < n; j++)
        {
             
            // Update frequency of
            // current subarray in map
            hm[arr[j]]++;
 
            // Increment count
            if (hm[arr[j]] == 1)
                count++;
 
            // Decrement count
            if (hm[arr[j]] == 2)
                count--;
 
            if (count == 0)
                return "No";
        }
    }
 
    // If all subarrays have at
    // least 1 unique element
    return "Yes";
}
 
// Driver Code
int main()
{
     
    // Given array arr[]
    int arr[] = { 1, 2, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << check(arr, N);
}
 
// This code is contributed by SURENDRA_GANGWAR

Java

// Java program for the above approach
 
import java.util.*;
import java.lang.*;
 
class GFG {
 
    // Function to check if all subarrays
    // have at least one unique element
    static String check(int arr[], int n)
    {
        // Generate all subarray
        for (int i = 0; i < n; i++) {
 
            // Store frequency of
            // subarray's elements
            Map hm
                = new HashMap<>();
 
            int count = 0;
 
            // Traverse the array over
            // the range [i, N]
            for (int j = i; j < n; j++) {
 
                // Update frequency of
                // current subarray in map
                hm.put(arr[j],
                       hm.getOrDefault(arr[j], 0) + 1);
 
                // Increment count
                if (hm.get(arr[j]) == 1)
                    count++;
 
                // Decrement count
                if (hm.get(arr[j]) == 2)
                    count--;
 
                if (count == 0)
                    return "No";
            }
        }
 
        // If all subarrays have at
        // least 1 unique element
        return "Yes";
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given array arr[]
        int[] arr = { 1, 2, 1 };
        int N = arr.length;
 
        // Function Call
        System.out.println(check(arr, N));
    }
}

Python3

# Python3 program for the above approach
 
# Function to check if all subarrays
# have at least one unique element
def check(arr, n):
     
    # Generate all subarray
    for i in range(n):
         
        # Store frequency of
        # subarray's elements
        hm = {}
 
        count = 0
 
        # Traverse the array over
        # the range [i, N]
        for j in range(i, n):
             
            # Update frequency of
            # current subarray in map
            hm[arr[j]] = hm.get(arr[j], 0) + 1
 
            # Increment count
            if (hm[arr[j]] == 1):
                count += 1
 
            # Decrement count
            if (hm[arr[j]] == 2):
                count -= 1
 
            if (count == 0):
                return "No"
 
    # If all subarrays have at
    # least 1 unique element
    return "Yes"
 
# Driver Code
if __name__ == '__main__':
     
    # Given array arr[]
    arr = [ 1, 2, 1 ]
    N = len(arr)
 
    # Function Call
    print(check(arr, N))
 
# This code is contributed by mohit kumar 29

C#

// C# program for the
// above approach
using System;
using System.Collections.Generic;
class GFG {
 
// Function to check if all
// subarrays have at least
// one unique element
static String check(int []arr,
                    int n)
{
  // Generate all subarray
  for (int i = 0; i < n; i++)
  {
    // Store frequency of
    // subarray's elements
    Dictionary hm =
               new Dictionary();
    int count = 0;
 
    // Traverse the array over
    // the range [i, N]
    for (int j = i; j < n; j++)
    {
      // Update frequency of
      // current subarray in map
      if(hm.ContainsKey((arr[j])))
        hm[arr[j]]++;
      else
        hm.Add(arr[j], 1);
 
      // Increment count
      if (hm[arr[j]] == 1)
        count++;
 
      // Decrement count
      if (hm[arr[j]] == 2)
        count--;
 
      if (count == 0)
        return "No";
    }
  }
 
  // If all subarrays have at
  // least 1 unique element
  return "Yes";
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given array []arr
  int[] arr = {1, 2, 1};
  int N = arr.Length;
 
  // Function Call
  Console.WriteLine(check(arr, N));
}
}
 
// This code is contributed by gauravrajput1
输出
Yes



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