📜  打印包含元素正负值的所有对

📅  最后修改于: 2021-04-25 00:11:16             🧑  作者: Mango

给定一个由不同整数组成的数组,请打印出数组中存在的具有正值和负值的数字的所有对。
注意:配对顺序无关紧要。

例子:

Input: arr[] = { 1, -3, 2, 3, 6, -1 }
Output: -1 1 -3 3

Input: arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 }
Output: -1 1 -4 4 -8 8 -9 9

天真的方法是运行两个循环,即使用外部循环考虑数组的每个元素,并使用内部循环在数组中搜索其对应的正/负值。同样,找到所有对。该方法的时间复杂度将为O(n 2 )。

更好的方法是使用排序,即先对数组排序,然后对每个负元素进行二进制搜索以找到其对应对象(+ ve号)。如果找到,请打印该对。如果当前元素为正,则中断该循环,因为此后将存在所有正数。

C++
// CPP program to find pairs of positive
// and negative values present in an array.
#include 
using namespace std;
  
void printPairs(int arr[], int n)
{
    bool pair_exists = false;
    // Sort the array
    sort(arr, arr + n);
  
    // Traverse the array
    for (int i = 0; i < n; i++) {
  
        // For every arr[i] < 0 element,
        // do a binary search for arr[i] > 0.
        if (arr[i] < 0) {
  
            // If found, print the pair.
            if (binary_search(arr, arr + n, -arr[i])) {
                cout << arr[i] << ", " << -arr[i] << endl;
  
                pair_exists = true;
            }
        }
  
        else
            break;
    }
  
    if (pair_exists == false)
        cout << "No such pair exists";
}
  
// Driver code
int main()
{
    int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    printPairs(arr, n);
  
    return 0;
}


Java
// Java program to find pairs 
// of positive and negative 
// values present in an array.
import java.util.*;
class GFG
{
static void printPairs(int arr[], int n)
{
    boolean pair_exists = false;
      
    // Sort the array
    Arrays.sort(arr);
  
    // Traverse the array
    for (int i = 0; i < n; i++) 
    {
  
        // For every arr[i] < 0 element,
        // do a binary search for arr[i] > 0.
        if (arr[i] < 0) 
        {
  
            // If found, print the pair.
            if (java.util.Arrays.binarySearch(arr, -arr[i])!=-1) 
            {
                System.out.println(arr[i] + ", " + -arr[i] );
  
                pair_exists = true;
            }
        }
  
        else
            break;
    }
  
    if (pair_exists == false)
        System.out.println("No such pair exists");
}
  
// Driver code
public static void main(String args[])
{
    int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 };
    int n =arr.length;
  
    printPairs(arr, n);
}
}
  
// This code is contributed
// by Arnab Kundu


Python 3
# Python3 program to find pairs of positive 
# and negative values present in an array. 
  
# function for binary search
def binary_search(a, x, lo=0, hi=None):
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        midval = a[mid]
        if midval < x:
            lo = mid+1
        elif midval > x: 
            hi = mid
        else:
            return mid
    return -1
  
def printPairs(arr, n): 
  
    pair_exists = False
    # Sort the array 
    arr.sort() 
  
    # Traverse the array 
    for i in range(n):
      
  
        # For every arr[i] < 0 element, 
        # do a binary search for arr[i] > 0. 
        if (arr[i] < 0): 
  
            # If found, print the pair. 
            if (binary_search(arr,-arr[i])): 
                print(arr[i] , ", " , -arr[i]) 
  
                pair_exists = True
          
          
  
        else:
            break
      
  
    if (pair_exists == False): 
        print("No such pair exists") 
  
  
# Driver code 
if __name__=='__main__':
    arr = [ 4, 8, 9, -4, 1, -1, -8, -9 ] 
    n = len(arr) 
  
    printPairs(arr, n) 
      
# this code is contributed by ash264


C#
// C# program to find pairs 
// of positive and negative 
// values present in an array. 
  
using System;
public class GFG{
  
static void printPairs(int []arr, int n) 
{ 
    bool pair_exists = false; 
      
    // Sort the array 
    Array.Sort(arr); 
  
    // Traverse the array 
    for (int i = 0; i < n; i++) 
    { 
  
        // For every arr[i] < 0 element, 
        // do a binary search for arr[i] > 0. 
        if (arr[i] < 0) 
        { 
  
            // If found, print the pair. 
            if (Array.BinarySearch(arr, -arr[i])!=-1) 
            { 
                Console.WriteLine(arr[i] + ", " + -arr[i] ); 
  
                pair_exists = true; 
            } 
        } 
  
        else
            break; 
    } 
  
    if (pair_exists == false) 
        Console.WriteLine("No such pair exists"); 
} 
  
// Driver code 
public static void Main() 
{ 
    int []arr = { 4, 8, 9, -4, 1, -1, -8, -9 }; 
    int n =arr.Length; 
  
    printPairs(arr, n); 
} 
} 
  
  
// This code is contributed by 29AjayKumar


C++
// CPP program to find pairs of positive
// and negative values present in an array
#include 
using namespace std;
  
// Function to print pairs of positive
// and negative values present in the array
void printPairs(int arr[], int n)
{
    unordered_set pairs;
    bool pair_exists = false;
  
    // Store all the positive elements
    // in the unordered_set
    for (int i = 0; i < n; i++)
        if (arr[i] > 0)
            pairs.insert(arr[i]);
  
    // Start traversing the array
    for (int i = 0; i < n; i++) {
  
        // Check if the positive value of current
        // element exists in the set or not
        if (arr[i] < 0)
            if (pairs.find(-arr[i]) != pairs.end())
  
            { // Print that pair
                cout << arr[i] << ", " << -arr[i] << endl;
  
                pair_exists = true;
            }
    }
  
    if (pair_exists == false)
        cout << "No such pair exists";
}
  
// Driver code
int main()
{
    int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    printPairs(arr, n);
    return 0;
}


Java
// Java program to find pairs of positive 
// and negative values present in an array 
import java.util.*;
class GFG
{
  
// Function to print pairs of positive 
// and negative values present in the array 
static void printPairs(int arr[], int n) 
{ 
    Set pairs = new HashSet(); 
    boolean pair_exists = false; 
  
    // Store all the positive elements 
    // in the unordered_set 
    for (int i = 0; i < n; i++) 
        if (arr[i] > 0) 
            pairs.add(arr[i]); 
  
    // Start traversing the array 
    for (int i = 0; i < n; i++) 
    { 
  
        // Check if the positive value of current 
        // element exists in the set or not 
        if (arr[i] < 0) 
            if (pairs.contains(-arr[i])) 
            { 
                // Print that pair 
                System.out.println(arr[i] + ", " + -arr[i]); 
  
                pair_exists = true; 
            } 
    } 
  
    if (pair_exists == false) 
        System.out.println("No such pair exists"); 
} 
  
// Driver code 
public static void main(String args[]) 
{ 
    int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 }; 
    int n = arr.length; 
  
    printPairs(arr, n); 
} 
}
  
// This code is contributed by Arnab Kundu


Python3
# Python3 program to find pairs of positive 
# and negative values present in an array 
  
# Function to print pairs of positive 
# and negative values present in the array 
def printPairs(arr, n): 
  
    pairs = set() 
    pair_exists = False
  
    # Store all the positive elements 
    # in the unordered_set 
    for i in range(0, n): 
        if arr[i] > 0: 
            pairs.add(arr[i]) 
  
    # Start traversing the array 
    for i in range(0, n): 
  
        # Check if the positive value of current 
        # element exists in the set or not 
        if arr[i] < 0:
            if (-arr[i]) in pairs: 
  
            # Print that pair 
                print("{}, {}".format(arr[i], -arr[i])) 
                pair_exists = True
  
    if pair_exists == False:
        print("No such pair exists")
  
# Driver code 
if __name__ == "__main__":
  
    arr = [4, 8, 9, -4, 1, -1, -8, -9] 
    n = len(arr) 
  
    printPairs(arr, n)
  
# This code is contributed by Rituraj Jain


C#
// C# program to find pairs of positive 
// and negative values present in an array 
using System;
using System.Collections.Generic;
  
class GFG
{
  
// Function to print pairs of positive 
// and negative values present in the array 
static void printPairs(int []arr, int n) 
{ 
    HashSet pairs = new HashSet(); 
    bool pair_exists = false; 
  
    // Store all the positive elements 
    // in the unordered_set 
    for (int i = 0; i < n; i++) 
        if (arr[i] > 0) 
            pairs.Add(arr[i]); 
  
    // Start traversing the array 
    for (int i = 0; i < n; i++) 
    { 
  
        // Check if the positive value of current 
        // element exists in the set or not 
        if (arr[i] < 0) 
            if (pairs.Contains(-arr[i])) 
            { 
                // Print that pair 
                Console.WriteLine(arr[i] + ", " + -arr[i]); 
  
                pair_exists = true; 
            } 
    } 
  
    if (pair_exists == false) 
        Console.WriteLine("No such pair exists"); 
} 
  
// Driver code 
public static void Main(String []args) 
{ 
    int []arr = { 4, 8, 9, -4, 1, -1, -8, -9 }; 
    int n = arr.Length; 
  
    printPairs(arr, n); 
} 
}
  
// This code is contributed by PrinciRaj1992


输出:
-9, 9
-8, 8
-4, 4
-1, 1

时间复杂度: O(nlogn)

一种有效的方法是使用哈希。以下是必需的步骤:

  • 开始遍历数组。
  • 将所有psoitve值存储在unordered_set中。
  • 检查每个否定元素,是否在集合中存在它们对应的肯定元素。
  • 如果是,请打印该对
  • 另外,维护一个标志以检查是否不存在这样的对。

C++

// CPP program to find pairs of positive
// and negative values present in an array
#include 
using namespace std;
  
// Function to print pairs of positive
// and negative values present in the array
void printPairs(int arr[], int n)
{
    unordered_set pairs;
    bool pair_exists = false;
  
    // Store all the positive elements
    // in the unordered_set
    for (int i = 0; i < n; i++)
        if (arr[i] > 0)
            pairs.insert(arr[i]);
  
    // Start traversing the array
    for (int i = 0; i < n; i++) {
  
        // Check if the positive value of current
        // element exists in the set or not
        if (arr[i] < 0)
            if (pairs.find(-arr[i]) != pairs.end())
  
            { // Print that pair
                cout << arr[i] << ", " << -arr[i] << endl;
  
                pair_exists = true;
            }
    }
  
    if (pair_exists == false)
        cout << "No such pair exists";
}
  
// Driver code
int main()
{
    int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    printPairs(arr, n);
    return 0;
}

Java

// Java program to find pairs of positive 
// and negative values present in an array 
import java.util.*;
class GFG
{
  
// Function to print pairs of positive 
// and negative values present in the array 
static void printPairs(int arr[], int n) 
{ 
    Set pairs = new HashSet(); 
    boolean pair_exists = false; 
  
    // Store all the positive elements 
    // in the unordered_set 
    for (int i = 0; i < n; i++) 
        if (arr[i] > 0) 
            pairs.add(arr[i]); 
  
    // Start traversing the array 
    for (int i = 0; i < n; i++) 
    { 
  
        // Check if the positive value of current 
        // element exists in the set or not 
        if (arr[i] < 0) 
            if (pairs.contains(-arr[i])) 
            { 
                // Print that pair 
                System.out.println(arr[i] + ", " + -arr[i]); 
  
                pair_exists = true; 
            } 
    } 
  
    if (pair_exists == false) 
        System.out.println("No such pair exists"); 
} 
  
// Driver code 
public static void main(String args[]) 
{ 
    int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 }; 
    int n = arr.length; 
  
    printPairs(arr, n); 
} 
}
  
// This code is contributed by Arnab Kundu

Python3

# Python3 program to find pairs of positive 
# and negative values present in an array 
  
# Function to print pairs of positive 
# and negative values present in the array 
def printPairs(arr, n): 
  
    pairs = set() 
    pair_exists = False
  
    # Store all the positive elements 
    # in the unordered_set 
    for i in range(0, n): 
        if arr[i] > 0: 
            pairs.add(arr[i]) 
  
    # Start traversing the array 
    for i in range(0, n): 
  
        # Check if the positive value of current 
        # element exists in the set or not 
        if arr[i] < 0:
            if (-arr[i]) in pairs: 
  
            # Print that pair 
                print("{}, {}".format(arr[i], -arr[i])) 
                pair_exists = True
  
    if pair_exists == False:
        print("No such pair exists")
  
# Driver code 
if __name__ == "__main__":
  
    arr = [4, 8, 9, -4, 1, -1, -8, -9] 
    n = len(arr) 
  
    printPairs(arr, n)
  
# This code is contributed by Rituraj Jain

C#

// C# program to find pairs of positive 
// and negative values present in an array 
using System;
using System.Collections.Generic;
  
class GFG
{
  
// Function to print pairs of positive 
// and negative values present in the array 
static void printPairs(int []arr, int n) 
{ 
    HashSet pairs = new HashSet(); 
    bool pair_exists = false; 
  
    // Store all the positive elements 
    // in the unordered_set 
    for (int i = 0; i < n; i++) 
        if (arr[i] > 0) 
            pairs.Add(arr[i]); 
  
    // Start traversing the array 
    for (int i = 0; i < n; i++) 
    { 
  
        // Check if the positive value of current 
        // element exists in the set or not 
        if (arr[i] < 0) 
            if (pairs.Contains(-arr[i])) 
            { 
                // Print that pair 
                Console.WriteLine(arr[i] + ", " + -arr[i]); 
  
                pair_exists = true; 
            } 
    } 
  
    if (pair_exists == false) 
        Console.WriteLine("No such pair exists"); 
} 
  
// Driver code 
public static void Main(String []args) 
{ 
    int []arr = { 4, 8, 9, -4, 1, -1, -8, -9 }; 
    int n = arr.Length; 
  
    printPairs(arr, n); 
} 
}
  
// This code is contributed by PrinciRaj1992
输出:
-4, 4
-1, 1
-8, 8
-9, 9

时间复杂度: O(n)