📌  相关文章
📜  检查是否可以从给定的数组中形成算术级数

📅  最后修改于: 2021-10-28 01:41:12             🧑  作者: Mango

给定一个由n 个整数组成的数组。任务是检查是否可以使用所有给定元素形成等差数列。如果可能,打印“是”,否则打印“否”。

例子:

Input : arr[] = {0, 12, 4, 8}
Output : Yes
Rearrange given array as {0, 4, 8, 12} 
which forms an arithmetic progression.

Input : arr[] = {12, 40, 11, 20}
Output : No

方法一(简单)
一个简单的解决方案是先找到最小的元素,然后找到第二小的元素并找出两者之间的差异。让这个差为 d。求差后,求第三小,第四小,依此类推。在找到每个第 i 个最小的最小值后(从第三个开始),找到当前元素的值与前一个元素的值之间的差值。如果差异与 d 不同,则返回 false。如果所有元素都具有相同的差异,则返回 true。此解决方案的时间复杂度为 O(n 2 )

方法二(使用排序)
这个想法是对给定的数组进行排序。排序后,检查连续元素之间的差异是否相同。如果所有差异都相同,则算术级数是可能的。

下面是这个方法的实现:

C++
// C++ program to check if a given array
// can form arithmetic progression
#include
using namespace std;
 
// Returns true if a permutation of arr[0..n-1]
// can form arithmetic progression
bool checkIsAP(int arr[], int n)
{
  if (n == 1)
    return true;
 
  // Sort array
  sort(arr, arr + n);
 
  // After sorting, difference between
  // consecutive elements must be same.
  int d = arr[1] - arr[0];
  for (int i=2; i


Java
// Java program to check if a given array
// can form arithmetic progression
import java.util.Arrays;
 
class GFG {
         
    // Returns true if a permutation of
    // arr[0..n-1] can form arithmetic
    // progression
    static boolean checkIsAP(int arr[], int n)
    {
        if (n == 1)
            return true;
         
        // Sort array
        Arrays.sort(arr);
         
        // After sorting, difference between
        // consecutive elements must be same.
        int d = arr[1] - arr[0];
        for (int i = 2; i < n; i++)
            if (arr[i] - arr[i-1] != d)
                return false;
         
        return true;
    }
     
    //driver code
    public static void main (String[] args)
    {
        int arr[] = { 20, 15, 5, 0, 10 };
        int n = arr.length;
     
        if(checkIsAP(arr, n))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
 
// This code is contributed by Anant Agarwal.


Python3
# Python3 program to check if a given
# array can form arithmetic progression
 
# Returns true if a permutation of arr[0..n-1]
# can form arithmetic progression
def checkIsAP(arr, n):
    if (n == 1): return True
 
    # Sort array
    arr.sort()
 
    # After sorting, difference between
    # consecutive elements must be same.
    d = arr[1] - arr[0]
    for i in range(2, n):
        if (arr[i] - arr[i-1] != d):
            return False
 
    return True
 
# Driver code
arr = [ 20, 15, 5, 0, 10 ]
n = len(arr)
print("Yes") if(checkIsAP(arr, n)) else print("No")
 
# This code is contributed by Anant Agarwal.


C#
// C# program to check if a given array
// can form arithmetic progression
using System;
 
class GFG {
         
    // Returns true if a permutation of
    // arr[0..n-1] can form arithmetic
    // progression
    static bool checkIsAP(int []arr, int n)
    {
        if (n == 1)
            return true;
         
        // Sort array
        Array.Sort(arr);
         
        // After sorting, difference between
        // consecutive elements must be same.
        int d = arr[1] - arr[0];
        for (int i = 2; i < n; i++)
            if (arr[i] - arr[i - 1] != d)
                return false;
         
        return true;
    }
     
    //Driver Code
    public static void Main ()
    {
        int []arr = {20, 15, 5, 0, 10};
        int n = arr.Length;
     
        if(checkIsAP(arr, n))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
 
// This code is contributed by vt_m.


PHP


Javascript


C++
// C++ program to check if a given array
// can form arithmetic progression
#include 
using namespace std;
 
// Returns true if a permutation of arr[0..n-1]
// can form arithmetic progression
bool checkIsAP(int arr[], int n)
{
    unordered_map hm;
    int smallest = INT_MAX, second_smallest = INT_MAX;
    for (int i = 0; i < n; i++) {
       
        // Find the smallest and and
        // update second smallest
        if (arr[i] < smallest) {
            second_smallest = smallest;
            smallest = arr[i];
        }
       
        // Find second smallest
        else if (arr[i] != smallest
                 && arr[i] < second_smallest)
            second_smallest = arr[i];
       
        // Check if the duplicate element found or not
        if (hm.find(arr[i]) == hm.end())
            hm[arr[i]]++;
       
        // If duplicate found then return false
        else
            return false;
    }
   
    // Find the difference between smallest and second
    // smallest
   
    int diff = second_smallest - smallest;
   
    // As we have used smallest and
    // second smallest,so we
    // should now only check for n-2 elements
    for (int i = 0; i < n - 1; i++) {
        if (hm.find(second_smallest) == hm.end())
            return false;
        second_smallest += diff;
    }
    return true;
}
 
// Driven Program
int main()
{
    int arr[] = { 20, 15, 5, 0, 10 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    (checkIsAP(arr, n)) ? (cout << "Yes" << endl)
                        : (cout << "No" << endl);
 
    return 0;
 
    // This code is contributed by Raman Jha
}


Python3
# Python3 program to check if a given array
# can form arithmetic progression
 
# Returns true if a permutation of arr[0..n-1]
# can form arithmetic progression
def checkIsAP(arr, n):
     
    hm = {}
    smallest = float('inf')
    second_smallest = float('inf')
     
    for i in range(n):
         
        # Find the smallest and and
        # update second smallest
        if (arr[i] < smallest):
            second_smallest = smallest
            smallest = arr[i]
       
        # Find second smallest
        elif (arr[i] != smallest and
              arr[i] < second_smallest):
            second_smallest = arr[i]
       
        # Check if the duplicate element found or not
        if arr[i] not in hm:
            hm[arr[i]] = 1
             
        # If duplicate found then return false
        else:
            return False
   
    # Find the difference between smallest
    # and second smallest
    diff = second_smallest - smallest
   
    # As we have used smallest and
    # second smallest,so we
    # should now only check for n-2 elements
    for i in range(n-1):
        if (second_smallest) not in hm:
            return False
             
        second_smallest += diff
     
    return True
 
# Driver code
arr = [ 20, 15, 5, 0, 10 ]
n = len(arr)
 
if (checkIsAP(arr, n)):
    print("Yes")
else:
    print("No")
     
# This code is contributed by rohitsingh07052


Javascript


Java
/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.*;
 
class GFG {
    public static void main(String[] args)
    {
        int[] arr = { 0, 12, 4, 8 };
        int n = arr.length;
        System.out.println(checkIsAP(arr, n));
    }
 
    static boolean checkIsAP(int arr[], int n)
    {
        HashSet set = new HashSet();
        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
        for (int i : arr) {
            max = Math.max(i, max);
            min = Math.min(i, min);
            set.add(i);
        }
        // FINDING THE COMMON DIFFERENCE
        int diff = (max - min) / (n - 1);
        int count = 0;
 
        // CHECK IF PRESENT IN THE HASHSET OR NOT
        while (set.contains(max)) {
            count++;
            max = max - diff;
        }
        if (count == arr.length)
            return true;
 
        return false;
    }
}


输出
Yes

时间复杂度: O(n Log n)。

方法三(使用哈希)

  1. 找出最小和第二小的元素
  2. 找出两个元素之间的不同。 d = second_smallest – 最小的
  3. 将所有元素存储在哈希图中,如果发现重复元素,则返回“NO”(可以与步骤 1 一起完成)。
  4. 现在从“第二小元素+d”开始,一一检查hashmap中算术级数的n-2项。如果缺少任何progression 值,则返回false。
  5. 循环结束后返回“YES”。

下面是这个方法的实现。

C++

// C++ program to check if a given array
// can form arithmetic progression
#include 
using namespace std;
 
// Returns true if a permutation of arr[0..n-1]
// can form arithmetic progression
bool checkIsAP(int arr[], int n)
{
    unordered_map hm;
    int smallest = INT_MAX, second_smallest = INT_MAX;
    for (int i = 0; i < n; i++) {
       
        // Find the smallest and and
        // update second smallest
        if (arr[i] < smallest) {
            second_smallest = smallest;
            smallest = arr[i];
        }
       
        // Find second smallest
        else if (arr[i] != smallest
                 && arr[i] < second_smallest)
            second_smallest = arr[i];
       
        // Check if the duplicate element found or not
        if (hm.find(arr[i]) == hm.end())
            hm[arr[i]]++;
       
        // If duplicate found then return false
        else
            return false;
    }
   
    // Find the difference between smallest and second
    // smallest
   
    int diff = second_smallest - smallest;
   
    // As we have used smallest and
    // second smallest,so we
    // should now only check for n-2 elements
    for (int i = 0; i < n - 1; i++) {
        if (hm.find(second_smallest) == hm.end())
            return false;
        second_smallest += diff;
    }
    return true;
}
 
// Driven Program
int main()
{
    int arr[] = { 20, 15, 5, 0, 10 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    (checkIsAP(arr, n)) ? (cout << "Yes" << endl)
                        : (cout << "No" << endl);
 
    return 0;
 
    // This code is contributed by Raman Jha
}

蟒蛇3

# Python3 program to check if a given array
# can form arithmetic progression
 
# Returns true if a permutation of arr[0..n-1]
# can form arithmetic progression
def checkIsAP(arr, n):
     
    hm = {}
    smallest = float('inf')
    second_smallest = float('inf')
     
    for i in range(n):
         
        # Find the smallest and and
        # update second smallest
        if (arr[i] < smallest):
            second_smallest = smallest
            smallest = arr[i]
       
        # Find second smallest
        elif (arr[i] != smallest and
              arr[i] < second_smallest):
            second_smallest = arr[i]
       
        # Check if the duplicate element found or not
        if arr[i] not in hm:
            hm[arr[i]] = 1
             
        # If duplicate found then return false
        else:
            return False
   
    # Find the difference between smallest
    # and second smallest
    diff = second_smallest - smallest
   
    # As we have used smallest and
    # second smallest,so we
    # should now only check for n-2 elements
    for i in range(n-1):
        if (second_smallest) not in hm:
            return False
             
        second_smallest += diff
     
    return True
 
# Driver code
arr = [ 20, 15, 5, 0, 10 ]
n = len(arr)
 
if (checkIsAP(arr, n)):
    print("Yes")
else:
    print("No")
     
# This code is contributed by rohitsingh07052

Javascript


输出
Yes

时间复杂度: O(n)
辅助空间: O(n)
感谢Chenna Rao提出这个方法,

方法四(使用计数排序)
如果可以修改给定的数组,我们可以减少方法 3 中所需的空间。

  1. 查找最小和第二小的元素。
  2. 找到 d = second_smallest – 最小的
  3. 从所有元素中减去最小元素。
  4. 现在,如果给定数组表示 AP,则所有元素都应为 i*d 形式,其中 i 从 0 到 n-1 变化。
  5. 用 d 一一划分所有减少的元素。如果任何元素不能被 d 整除,则返回 false。
  6. 现在如果数组代表 AP,它必须是从 0 到 n-1 的数字排列。我们可以使用计数排序轻松检查这一点。

方法 5(单次散列)

基本思想是通过找出数组的最大和最小元素来找到AP的共同差异。之后从最大值开始,通过共同的差异继续减小值,同时检查这个新值是否存在于哈希图中。如果在任何时候该值不存在于 hashset 中,则中断循环。循环中断后的理想情况是所有 n 个元素都被覆盖,如果是,则返回 true 否则返回 false。

Java

/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.*;
 
class GFG {
    public static void main(String[] args)
    {
        int[] arr = { 0, 12, 4, 8 };
        int n = arr.length;
        System.out.println(checkIsAP(arr, n));
    }
 
    static boolean checkIsAP(int arr[], int n)
    {
        HashSet set = new HashSet();
        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
        for (int i : arr) {
            max = Math.max(i, max);
            min = Math.min(i, min);
            set.add(i);
        }
        // FINDING THE COMMON DIFFERENCE
        int diff = (max - min) / (n - 1);
        int count = 0;
 
        // CHECK IF PRESENT IN THE HASHSET OR NOT
        while (set.contains(max)) {
            count++;
            max = max - diff;
        }
        if (count == arr.length)
            return true;
 
        return false;
    }
}
输出
true

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

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