📌  相关文章
📜  数组中的所有元素是否相同?

📅  最后修改于: 2021-10-27 07:13:34             🧑  作者: Mango

给定一个数组,检查数组中的所有元素是否相同。

例子:

Input : "Geeks", "for", "Geeks"
Output : Not all Elements are Same

Input : 1, 1, 1, 1, 1
Output : All Elements are Same

方法一(Hashing)我们创建一个空的HashSet,把所有的元素都插入进去,最后看看HashSet的大小是否为1。

C++
//c++ program to check if all array are same or not
#include
 
using namespace std;
 
bool areSame(int a[],int n)
{
    unordered_map m;//hash map to store the frequency od every
                             //element
     
    for(int i=0;i


Java
// Java program to check if all array elements are
// same or not.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
 
public class SameElements {
public static boolean areSame(Integer arr[])
    {
        // Put all array elements in a HashSet
        Set s = new HashSet<>(Arrays.asList(arr));
 
        // If all elements are same, size of
        // HashSet should be 1. As HashSet contains only distinct values.
        return (s.size() == 1);
    }
 
    // Driver code
public static void main(String[] args)
    {
        Integer[] arr = { 1, 2, 3, 2 };
        if (areSame(arr))
            System.out.println("All Elements are Same");
        else
            System.out.println("Not all Elements are Same");
    }
}


Python3
# Python 3 program to check if all
# array are same or not
def areSame(a, n):
    m = {i:0 for i in range(len(a))}
     
    # hash map to store the frequency
    # of every element
     
    for i in range(n):
        m[a[i]] += 1
     
    if(len(m) == 1):
        return True
    else:
        return False
 
# Driver code
if __name__ == '__main__':
    arr = [1, 2, 3, 2]
     
    n = len(arr)
     
    if(areSame(arr, n)):
        print("All Elements are Same")
    else:
        print("Not all Elements are Same")
 
# This code is contributed by
# Shashank_Sharma


C#
// C# program to check if all array elements
// are same or not.
using System;
using System.Collections.Generic;
  
class GFG{
     
public static bool areSame(int []arr)
{
     
    // Put all array elements in a HashSet
    HashSet s = new HashSet();
    for(int i = 0; i < arr.Length; i++)
        s.Add(arr[i]);
     
    // If all elements are same, size of
    // HashSet should be 1. As HashSet
    // contains only distinct values.
    return (s.Count == 1);
}
 
// Driver code
public static void Main(String[] args)
{
    int[] arr = { 1, 2, 3, 2 };
     
    if (areSame(arr))
        Console.WriteLine("All Elements are Same");
    else
        Console.WriteLine("Not all Elements are Same");
}
}
 
// This code is contributed by Amit Katiyar


Javascript


C++
// C++ Program to implement
// the above approach
#include 
using namespace std;
 
bool areSame(int arr[],
             int n)
{
  int first = arr[0];
 
  for (int i = 1; i < n; i++)
    if (arr[i] != first)
      return 0;
  return 1;
}
 
// Driver code
int main()
{
  int arr[] = {1, 2, 3, 2};
  int n = sizeof(arr) /
          sizeof(arr[0]);
  if (areSame(arr, n))
    cout << "All Elements are Same";
  else
    cout << "Not all Elements are Same";
}
 
// This code is contributed by gauravrajput1


Java
// Java program to check if all array elements are
// same or not.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
 
public class SameElements {
public static boolean areSame(Integer arr[])
    {
       Integer first = arr[0];
       for (int i=1; i


Python3
# Python3 program to check
# if all array elements are
# same or not.
def areSame(arr):
   
    first = arr[0];
     
    for i in range(1, len(arr)):
        if (arr[i] != first):
            return False;
           
    return True;
 
# Driver code
if __name__ == '__main__':
   
    arr = [1, 2, 3, 2];
     
    if (areSame(arr)):
        print("All Elements are Same");
    else:
        print("Not all Elements are Same");
 
# This code is contributed by Rajput-Ji


C#
// C# program to check if all
// array elements are same or not.
using System;
class SameElements{
   
static bool areSame(int []arr)
{
  int first = arr[0];
   
  for (int i = 1;
           i < arr.Length; i++)
    if (arr[i] != first)
      return false;
  return true;
}
 
// Driver code
public static void Main(String[] args)
{
  int[] arr = {1, 2, 3, 2};
   
  if (areSame(arr))
    Console.WriteLine("All Elements are Same");
  else
    Console.WriteLine("Not all Elements are Same");
}
}
 
// This code is contributed by 29AjayKumar


Javascript


输出
Not all Elements are Same

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

方法二(与第一种比较)思路很简单。我们将所有其他元素与第一个进行比较。如果所有都与第一个匹配,我们返回 true。否则我们返回false。

C++

// C++ Program to implement
// the above approach
#include 
using namespace std;
 
bool areSame(int arr[],
             int n)
{
  int first = arr[0];
 
  for (int i = 1; i < n; i++)
    if (arr[i] != first)
      return 0;
  return 1;
}
 
// Driver code
int main()
{
  int arr[] = {1, 2, 3, 2};
  int n = sizeof(arr) /
          sizeof(arr[0]);
  if (areSame(arr, n))
    cout << "All Elements are Same";
  else
    cout << "Not all Elements are Same";
}
 
// This code is contributed by gauravrajput1

Java

// Java program to check if all array elements are
// same or not.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
 
public class SameElements {
public static boolean areSame(Integer arr[])
    {
       Integer first = arr[0];
       for (int i=1; i

蟒蛇3

# Python3 program to check
# if all array elements are
# same or not.
def areSame(arr):
   
    first = arr[0];
     
    for i in range(1, len(arr)):
        if (arr[i] != first):
            return False;
           
    return True;
 
# Driver code
if __name__ == '__main__':
   
    arr = [1, 2, 3, 2];
     
    if (areSame(arr)):
        print("All Elements are Same");
    else:
        print("Not all Elements are Same");
 
# This code is contributed by Rajput-Ji

C#

// C# program to check if all
// array elements are same or not.
using System;
class SameElements{
   
static bool areSame(int []arr)
{
  int first = arr[0];
   
  for (int i = 1;
           i < arr.Length; i++)
    if (arr[i] != first)
      return false;
  return true;
}
 
// Driver code
public static void Main(String[] args)
{
  int[] arr = {1, 2, 3, 2};
   
  if (areSame(arr))
    Console.WriteLine("All Elements are Same");
  else
    Console.WriteLine("Not all Elements are Same");
}
}
 
// This code is contributed by 29AjayKumar

Javascript


输出
Not all Elements are Same

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

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程