📜  排序数组中的绝对唯一计数

📅  最后修改于: 2021-04-29 11:01:51             🧑  作者: Mango

给定一个有序的整数数组,返回数组元素之间不同的绝对值的数量。输入可以包含重复值。
例子:

Input: [-3, -2, 0, 3, 4, 5]
Output: 5
There are 5 distinct absolute values
among the elements of this array, i.e.
0, 2, 3, 4 and 5)

Input:  [-1, -1, -1, -1, 0, 1, 1, 1, 1]
Output: 2

Input:  [-1, -1, -1, -1, 0]
Output: 2

Input:  [0, 0, 0]
Output: 1 

该解决方案应该只扫描输入数组一次,并且不应该使用任何额外的空间。即,预期时间复杂度为O(n),辅助空间为O(1)。

一种简单的解决方案是使用set。对于输入数组的每个元素,我们将其绝对值插入集合中。由于set不支持重复元素,因此元素的绝对值将仅插入一次。因此,所需的计数是集合的大小。
以下是该想法的实现。

C++
// C++ program to find absolute distinct
// count of an array in O(n) time.
#include 
using namespace std;
 
// The function returns number of
// distinct absolute values among
// the elements of the array
int distinctCount(int arr[], int n)
{
    unordered_set s;
 
    // Note that set keeps only one
    // copy even if we try to insert
    // multiple values
    for (int i = 0 ; i < n; i++)
        s.insert(abs(arr[i]));
 
    return s.size();
}
 
// Driver code
int main()
{
    int arr[] = {-2, -1, 0, 1, 1};
    int n = sizeof(arr)/sizeof(arr[0]);
 
    cout << "Count of absolute distinct values : "
         << distinctCount(arr, n);
 
    return 0;
}


Java
// java code to find absolute distinct
// count of an array in O(n) time.
import java.util.*;
 
class GFG
{
    // The function returns number of
    // distinct absolute values among
    // the elements of the array
    static int distinctCount(int arr[], int n)
    {
        Set s = new HashSet ();
 
        // Note that set keeps only one
        // copy even if we try to insert
        // multiple values
        for (int i = 0 ; i < n; i++)
        s.add(Math.abs(arr[i]));
         
        return s.size();
         
    }
     
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = {-2, -1, 0, 1, 1};
        int n = arr.length;
 
        System.out.println("Count of absolute distinct values : "
                           + distinctCount(arr, n));
         
    }
}
 
// This code is contributed by prerna saini


Python3
# Python3 code to find absolute distinct
# count of an array in O(n) time.
 
# This function returns number of
# distinct absolute values among
# the elements of the array
def distinctCount(arr, n):
    s = set()
     
    # set keeps all unique elements
    for i in range(n):
        s.add(abs(arr[i]))
    return len(s)
 
# Driver Code
arr = [-2, -1, 0, 1, 1]
n = len(arr)
print("Count of absolute distinct values:",
                     distinctCount(arr, n))
 
# This code is contributed
# by Adarsh_Verma


C#
// C# code to find absolute distinct
// count of an array in O(n) time.
using System;
using System.Collections.Generic;
 
class GFG
{
    // The function returns number of
    // distinct absolute values among
    // the elements of the array
    static int distinctCount(int []arr, int n)
    {
        HashSet s = new HashSet();
 
        // Note that set keeps only one
        // copy even if we try to insert
        // multiple values
        for (int i = 0 ; i < n; i++)
        s.Add(Math.Abs(arr[i]));
         
        return s.Count;
         
    }
     
    // Driver code
    public static void Main()
    {
        int []arr = {-2, -1, 0, 1, 1};
        int n = arr.Length;
 
        Console.Write("Count of absolute distinct values : "
                        + distinctCount(arr, n));
         
    }
}
 
// This code is contributed by PrinciRaj1992


C++
// C++ program to find absolute distinct
// count of an array using O(1) space.
#include 
using namespace std;
 
// The function returns return number
// of distinct absolute values
// among the elements of the array
int distinctCount(int arr[], int n)
{
    // initialize count as number of elements
    int count = n;
    int i = 0, j = n - 1, sum = 0;
 
    while (i < j)
    {
        // Remove duplicate elements from the
        // left of the current window (i, j)
        // and also decrease the count
        while (i != j && arr[i] == arr[i + 1])
            count--, i++;
 
        // Remove duplicate elements from the
        // right of the current window (i, j)
        // and also decrease the count
        while (i != j && arr[j] == arr[j - 1])
            count--, j--;
 
        // break if only one element is left
        if (i == j)
            break;
 
        // Now look for the zero sum pair
        // in current window (i, j)
        sum = arr[i] + arr[j];
 
        if (sum == 0)
        {
            // decrease the count if (positive,
            // negative) pair is encountered
            count--;
            i++, j--;
        }
        else if(sum < 0)
            i++;
        else
            j--;
    }
 
    return count;
}
 
// Driver code
int main()
{
    int arr[] = {-2, -1, 0, 1, 1};
    int n = sizeof(arr)/sizeof(arr[0]);
 
    cout << "Count of absolute distinct values : "
         << distinctCount(arr, n);
 
    return 0;
}


Java
// Java program to find absolute distinct
// count of an array using O(1) space.
 
import java.io.*;
 
class GFG {
     
     
// The function returns return number
// of distinct absolute values
// among the elements of the array
static int distinctCount(int arr[], int n)
{
    // initialize count as number of elements
    int count = n;
    int i = 0, j = n - 1, sum = 0;
 
    while (i < j)
    {
        // Remove duplicate elements from the
        // left of the current window (i, j)
        // and also decrease the count
        while (i != j && arr[i] == arr[i + 1])
        {
            count--;
            i++;
        }
        // Remove duplicate elements from the
        // right of the current window (i, j)
        // and also decrease the count
        while (i != j && arr[j] == arr[j - 1])
        {
            count--;
            j--;
        }
        // break if only one element is left
        if (i == j)
            break;
 
        // Now look for the zero sum pair
        // in current window (i, j)
        sum = arr[i] + arr[j];
 
        if (sum == 0)
        {
            // decrease the count if (positive,
            // negative) pair is encountered
            count--;
            i++;
            j--;
        }
        else if(sum < 0)
            i++;
        else
            j--;
    }
 
    return count;
}
 
// Driver code
     
    public static void main (String[] args) {
     
    int arr[] = {-2, -1, 0, 1, 1};
    int n = arr.length;
 
    System.out.println ("Count of absolute distinct values : "+
             distinctCount(arr, n));
         
         
    }
}


Python3
# Python3 program to find absolute distinct
# count of an array using O(1) space.
 
# The function returns return number
# of distinct absolute values
# among the elements of the array
def distinctCount(arr, n):
 
    # initialize count as number of elements
    count = n;
    i = 0; j = n - 1; sum = 0;
 
    while (i < j):
         
        # Remove duplicate elements from the
        # left of the current window (i, j)
        # and also decrease the count
        while (i != j and arr[i] == arr[i + 1]):
            count = count - 1;
            i = i + 1;
 
        # Remove duplicate elements from the
        # right of the current window (i, j)
        # and also decrease the count
        while (i != j and arr[j] == arr[j - 1]):
            count = count - 1;
            j = j - 1;
 
        # break if only one element is left
        if (i == j):
            break;
 
        # Now look for the zero sum pair
        # in current window (i, j)
        sum = arr[i] + arr[j];
 
        if (sum == 0):
         
            # decrease the count if (positive,
            # negative) pair is encountered
            count = count - 1;
            i = i + 1;
            j = j - 1;
             
        elif(sum < 0):
            i = i + 1;
        else:
            j = j - 1;
     
    return count;
 
 
# Driver code
arr = [-2, -1, 0, 1, 1];
n = len(arr);
 
print("Count of absolute distinct values : ",
                      distinctCount(arr, n));
 
# This code is contributed
# by Akanksha Rai


C#
//C# program to find absolute distinct
// count of an array using O(1) space.
using System;
 
class GFG {
     
     
// The function returns return number
// of distinct absolute values
// among the elements of the array
static int distinctCount(int []arr, int n)
{
    // initialize count as number of elements
    int count = n;
    int i = 0, j = n - 1, sum = 0;
 
    while (i < j)
    {
        // Remove duplicate elements from the
        // left of the current window (i, j)
        // and also decrease the count
        while (i != j && arr[i] == arr[i + 1])
        {
            count--;
            i++;
        }
        // Remove duplicate elements from the
        // right of the current window (i, j)
        // and also decrease the count
        while (i != j && arr[j] == arr[j - 1])
        {
            count--;
            j--;
        }
        // break if only one element is left
        if (i == j)
            break;
 
        // Now look for the zero sum pair
        // in current window (i, j)
        sum = arr[i] + arr[j];
 
        if (sum == 0)
        {
            // decrease the count if (positive,
            // negative) pair is encountered
            count--;
            i++;
            j--;
        }
        else if(sum < 0)
            i++;
        else
            j--;
    }
 
    return count;
}
 
// Driver code
     
    public static void Main () {
     
    int []arr = {-2, -1, 0, 1, 1};
    int n = arr.Length;
 
    Console.WriteLine("Count of absolute distinct values : "+
            distinctCount(arr, n));
         
    // This code is contributed by inder_verma   
    }
}


PHP


Javascript


输出 :

Count of absolute distinct values : 3

时间复杂度: O(n)
辅助空间: O(n)
上面的实现占用O(n)额外空间,如何在O(1)额外空间中做呢?
这个想法是利用数组已经被排序的事实。我们将不同元素的数量初始化为数组中元素的数量。我们从数组的两个角开始,使用两个索引变量,然后在输入数组中检查sum是否为0的对。如果发现sum为0的对或遇到重复项,我们将减少不同元素的计数。最后,我们返回更新后的元素的数量。数数。
下面是上述方法的实现。

C++

// C++ program to find absolute distinct
// count of an array using O(1) space.
#include 
using namespace std;
 
// The function returns return number
// of distinct absolute values
// among the elements of the array
int distinctCount(int arr[], int n)
{
    // initialize count as number of elements
    int count = n;
    int i = 0, j = n - 1, sum = 0;
 
    while (i < j)
    {
        // Remove duplicate elements from the
        // left of the current window (i, j)
        // and also decrease the count
        while (i != j && arr[i] == arr[i + 1])
            count--, i++;
 
        // Remove duplicate elements from the
        // right of the current window (i, j)
        // and also decrease the count
        while (i != j && arr[j] == arr[j - 1])
            count--, j--;
 
        // break if only one element is left
        if (i == j)
            break;
 
        // Now look for the zero sum pair
        // in current window (i, j)
        sum = arr[i] + arr[j];
 
        if (sum == 0)
        {
            // decrease the count if (positive,
            // negative) pair is encountered
            count--;
            i++, j--;
        }
        else if(sum < 0)
            i++;
        else
            j--;
    }
 
    return count;
}
 
// Driver code
int main()
{
    int arr[] = {-2, -1, 0, 1, 1};
    int n = sizeof(arr)/sizeof(arr[0]);
 
    cout << "Count of absolute distinct values : "
         << distinctCount(arr, n);
 
    return 0;
}

Java

// Java program to find absolute distinct
// count of an array using O(1) space.
 
import java.io.*;
 
class GFG {
     
     
// The function returns return number
// of distinct absolute values
// among the elements of the array
static int distinctCount(int arr[], int n)
{
    // initialize count as number of elements
    int count = n;
    int i = 0, j = n - 1, sum = 0;
 
    while (i < j)
    {
        // Remove duplicate elements from the
        // left of the current window (i, j)
        // and also decrease the count
        while (i != j && arr[i] == arr[i + 1])
        {
            count--;
            i++;
        }
        // Remove duplicate elements from the
        // right of the current window (i, j)
        // and also decrease the count
        while (i != j && arr[j] == arr[j - 1])
        {
            count--;
            j--;
        }
        // break if only one element is left
        if (i == j)
            break;
 
        // Now look for the zero sum pair
        // in current window (i, j)
        sum = arr[i] + arr[j];
 
        if (sum == 0)
        {
            // decrease the count if (positive,
            // negative) pair is encountered
            count--;
            i++;
            j--;
        }
        else if(sum < 0)
            i++;
        else
            j--;
    }
 
    return count;
}
 
// Driver code
     
    public static void main (String[] args) {
     
    int arr[] = {-2, -1, 0, 1, 1};
    int n = arr.length;
 
    System.out.println ("Count of absolute distinct values : "+
             distinctCount(arr, n));
         
         
    }
}

Python3

# Python3 program to find absolute distinct
# count of an array using O(1) space.
 
# The function returns return number
# of distinct absolute values
# among the elements of the array
def distinctCount(arr, n):
 
    # initialize count as number of elements
    count = n;
    i = 0; j = n - 1; sum = 0;
 
    while (i < j):
         
        # Remove duplicate elements from the
        # left of the current window (i, j)
        # and also decrease the count
        while (i != j and arr[i] == arr[i + 1]):
            count = count - 1;
            i = i + 1;
 
        # Remove duplicate elements from the
        # right of the current window (i, j)
        # and also decrease the count
        while (i != j and arr[j] == arr[j - 1]):
            count = count - 1;
            j = j - 1;
 
        # break if only one element is left
        if (i == j):
            break;
 
        # Now look for the zero sum pair
        # in current window (i, j)
        sum = arr[i] + arr[j];
 
        if (sum == 0):
         
            # decrease the count if (positive,
            # negative) pair is encountered
            count = count - 1;
            i = i + 1;
            j = j - 1;
             
        elif(sum < 0):
            i = i + 1;
        else:
            j = j - 1;
     
    return count;
 
 
# Driver code
arr = [-2, -1, 0, 1, 1];
n = len(arr);
 
print("Count of absolute distinct values : ",
                      distinctCount(arr, n));
 
# This code is contributed
# by Akanksha Rai

C#

//C# program to find absolute distinct
// count of an array using O(1) space.
using System;
 
class GFG {
     
     
// The function returns return number
// of distinct absolute values
// among the elements of the array
static int distinctCount(int []arr, int n)
{
    // initialize count as number of elements
    int count = n;
    int i = 0, j = n - 1, sum = 0;
 
    while (i < j)
    {
        // Remove duplicate elements from the
        // left of the current window (i, j)
        // and also decrease the count
        while (i != j && arr[i] == arr[i + 1])
        {
            count--;
            i++;
        }
        // Remove duplicate elements from the
        // right of the current window (i, j)
        // and also decrease the count
        while (i != j && arr[j] == arr[j - 1])
        {
            count--;
            j--;
        }
        // break if only one element is left
        if (i == j)
            break;
 
        // Now look for the zero sum pair
        // in current window (i, j)
        sum = arr[i] + arr[j];
 
        if (sum == 0)
        {
            // decrease the count if (positive,
            // negative) pair is encountered
            count--;
            i++;
            j--;
        }
        else if(sum < 0)
            i++;
        else
            j--;
    }
 
    return count;
}
 
// Driver code
     
    public static void Main () {
     
    int []arr = {-2, -1, 0, 1, 1};
    int n = arr.Length;
 
    Console.WriteLine("Count of absolute distinct values : "+
            distinctCount(arr, n));
         
    // This code is contributed by inder_verma   
    }
}

的PHP


Java脚本


输出 :

Count of absolute distinct values : 3