编写一个程序,给定一个由 n 个数字组成的数组 A[] 和另一个数字 x,确定 A[] 中是否存在两个元素之和恰好为 x。
例子:
Input: arr[] = {0, -1, 2, -3, 1}
sum = -2
Output: -3, 1
If we calculate the sum of the output,
1 + (-3) = -2
Input: arr[] = {1, -2, 1, 0, 5}
sum = 0
Output: -1
No valid pair exists.
方法 1 :排序和两点技术。
方法:解决此问题的一个棘手方法是使用两点技术。但是对于使用两个指针技术,必须对数组进行排序。一旦数组被排序,就可以使用两个指针,分别标记数组的开始和结束。如果该和比这两种元素的总和,移位右指针以减少所需之和的值以及如果该总和大于所要求的值较小,移位左指针,以增加所需要的和的值。让我们通过一个例子来理解这一点。
Let an array be {1, 4, 45, 6, 10, -8} and sum to find be 16
After sorting the array
A = {-8, 1, 4, 6, 10, 45}
Now, increment ‘l’ when the sum of the pair is less than the required sum and decrement ‘r’ when the sum of the pair is more than the required sum.
This is because when the sum is less than the required sum then to get the number which could increase the sum of pair, start moving from left to right(also sort the array) thus “l++” and vice versa.
Initialize l = 0, r = 5
A[l] + A[r] ( -8 + 45) > 16 => decrement r. Now r = 4
A[l] + A[r] ( -8 + 10) increment l. Now l = 1
A[l] + A[r] ( 1 + 10) increment l. Now l = 2
A[l] + A[r] ( 4 + 10) increment l. Now l = 3
A[l] + A[r] ( 6 + 10) == 16 => Found candidates (return 1)
注意:如果超过一对具有给定的总和,则该算法仅报告一对。不过可以很容易地为此扩展。
算法:
- hasArrayTwoCandidates (A[], ar_size, sum)
- 按非递减顺序对数组进行排序。
- 初始化两个索引变量以找到候选
排序数组中的元素。- 先初始化到最左边的索引:l = 0
- 初始化第二个最右边的索引:r = ar_size-1
- 当 l < r 时循环。
- 如果 (A[l] + A[r] == sum) 则返回 1
- 否则 if( A[l] + A[r] < sum ) then l++
- 否则 r–
- 整个数组中没有候选人 – 返回 0
C++
// C++ program to check if given array
// has 2 elements whose sum is equal
// to the given value
#include
using namespace std;
// Function to check if array has 2 elements
// whose sum is equal to the given value
bool hasArrayTwoCandidates(int A[], int arr_size,
int sum)
{
int l, r;
/* Sort the elements */
sort(A, A + arr_size);
/* Now look for the two candidates in
the sorted array*/
l = 0;
r = arr_size - 1;
while (l < r) {
if (A[l] + A[r] == sum)
return 1;
else if (A[l] + A[r] < sum)
l++;
else // A[i] + A[j] > sum
r--;
}
return 0;
}
/* Driver program to test above function */
int main()
{
int A[] = { 1, 4, 45, 6, 10, -8 };
int n = 16;
int arr_size = sizeof(A) / sizeof(A[0]);
// Function calling
if (hasArrayTwoCandidates(A, arr_size, n))
cout << "Array has two elements"
" with given sum";
else
cout << "Array doesn't have two"
" elements with given sum";
return 0;
}
C
// C program to check if given array
// has 2 elements whose sum is equal
// to the given value
#include
#define bool int
void quickSort(int*, int, int);
bool hasArrayTwoCandidates(
int A[], int arr_size, int sum)
{
int l, r;
/* Sort the elements */
quickSort(A, 0, arr_size - 1);
/* Now look for the two candidates in the sorted
array*/
l = 0;
r = arr_size - 1;
while (l < r) {
if (A[l] + A[r] == sum)
return 1;
else if (A[l] + A[r] < sum)
l++;
else // A[i] + A[j] > sum
r--;
}
return 0;
}
/* FOLLOWING FUNCTIONS ARE ONLY FOR SORTING
PURPOSE */
void exchange(int* a, int* b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int partition(int A[], int si, int ei)
{
int x = A[ei];
int i = (si - 1);
int j;
for (j = si; j <= ei - 1; j++) {
if (A[j] <= x) {
i++;
exchange(&A[i], &A[j]);
}
}
exchange(&A[i + 1], &A[ei]);
return (i + 1);
}
/* Implementation of Quick Sort
A[] --> Array to be sorted
si --> Starting index
ei --> Ending index
*/
void quickSort(int A[], int si, int ei)
{
int pi; /* Partitioning index */
if (si < ei) {
pi = partition(A, si, ei);
quickSort(A, si, pi - 1);
quickSort(A, pi + 1, ei);
}
}
/* Driver program to test above function */
int main()
{
int A[] = { 1, 4, 45, 6, 10, -8 };
int n = 16;
int arr_size = 6;
if (hasArrayTwoCandidates(A, arr_size, n))
printf("Array has two elements with given sum");
else
printf("Array doesn't have two elements with given sum");
getchar();
return 0;
}
Java
// Java program to check if given array
// has 2 elements whose sum is equal
// to the given value
import java.util.*;
class GFG {
// Function to check if array has 2 elements
// whose sum is equal to the given value
static boolean hasArrayTwoCandidates(
int A[],
int arr_size, int sum)
{
int l, r;
/* Sort the elements */
Arrays.sort(A);
/* Now look for the two candidates
in the sorted array*/
l = 0;
r = arr_size - 1;
while (l < r) {
if (A[l] + A[r] == sum)
return true;
else if (A[l] + A[r] < sum)
l++;
else // A[i] + A[j] > sum
r--;
}
return false;
}
// Driver code
public static void main(String args[])
{
int A[] = { 1, 4, 45, 6, 10, -8 };
int n = 16;
int arr_size = A.length;
// Function calling
if (hasArrayTwoCandidates(A, arr_size, n))
System.out.println("Array has two "
+ "elements with given sum");
else
System.out.println("Array doesn't have "
+ "two elements with given sum");
}
}
Python
# Python program to check for the sum
# condition to be satisified
def hasArrayTwoCandidates(A, arr_size, sum):
# sort the array
quickSort(A, 0, arr_size-1)
l = 0
r = arr_size-1
# traverse the array for the two elements
while l Array to be sorted
# si --> Starting index
# ei --> Ending index
def quickSort(A, si, ei):
if si < ei:
pi = partition(A, si, ei)
quickSort(A, si, pi-1)
quickSort(A, pi + 1, ei)
# Utility function for partitioning
# the array(used in quick sort)
def partition(A, si, ei):
x = A[ei]
i = (si-1)
for j in range(si, ei):
if A[j] <= x:
i += 1
# This operation is used to swap
# two variables is python
A[i], A[j] = A[j], A[i]
A[i + 1], A[ei] = A[ei], A[i + 1]
return i + 1
# Driver program to test the functions
A = [1, 4, 45, 6, 10, -8]
n = 16
if (hasArrayTwoCandidates(A, len(A), n)):
print("Array has two elements with the given sum")
else:
print("Array doesn't have two elements
with the given sum")
## This code is contributed by __Devesh Agrawal__
C#
// C# program to check for pair
// in A[] with sum as x
using System;
class GFG {
static bool hasArrayTwoCandidates(int[] A,
int arr_size, int sum)
{
int l, r;
/* Sort the elements */
sort(A, 0, arr_size - 1);
/* Now look for the two candidates
in the sorted array*/
l = 0;
r = arr_size - 1;
while (l < r) {
if (A[l] + A[r] == sum)
return true;
else if (A[l] + A[r] < sum)
l++;
else // A[i] + A[j] > sum
r--;
}
return false;
}
/* Below functions are only to sort the
array using QuickSort */
/* This function takes last element as pivot,
places the pivot element at its correct
position in sorted array, and places all
smaller (smaller than pivot) to left of
pivot and all greater elements to right
of pivot */
static int partition(int[] arr, int low, int high)
{
int pivot = arr[high];
// index of smaller element
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
// If current element is smaller
// than or equal to pivot
if (arr[j] <= pivot) {
i++;
// swap arr[i] and arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// swap arr[i+1] and arr[high] (or pivot)
int temp1 = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp1;
return i + 1;
}
/* The main function that
implements QuickSort()
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
static void sort(int[] arr, int low, int high)
{
if (low < high) {
/* pi is partitioning index, arr[pi]
is now at right place */
int pi = partition(arr, low, high);
// Recursively sort elements before
// partition and after partition
sort(arr, low, pi - 1);
sort(arr, pi + 1, high);
}
}
// Driver code
public static void Main()
{
int[] A = { 1, 4, 45, 6, 10, -8 };
int n = 16;
int arr_size = 6;
if (hasArrayTwoCandidates(A, arr_size, n))
Console.Write("Array has two elements"
+ " with given sum");
else
Console.Write("Array doesn't have "
+ "two elements with given sum");
}
}
// This code is contributed by Sam007
PHP
sum
$r--;
}
return 0;
}
// Driver Code
$A = array (1, 4, 45, 6, 10, -8);
$n = 16;
$arr_size = sizeof($A);
// Function calling
if(hasArrayTwoCandidates($A, $arr_size, $n))
echo "Array has two elements " .
"with given sum";
else
echo "Array doesn't have two " .
"elements with given sum";
// This code is contributed by m_kit
?>
Javascript
C++
// C++ program to check if given array
// has 2 elements whose sum is equal
// to the given value
#include
using namespace std;
void printPairs(int arr[], int arr_size, int sum)
{
unordered_set s;
for (int i = 0; i < arr_size; i++)
{
int temp = sum - arr[i];
if (s.find(temp) != s.end())
cout << "Pair with given sum "
<< sum << " is (" << arr[i] << ","
<< temp << ")" << endl;
s.insert(arr[i]);
}
}
/* Driver Code */
int main()
{
int A[] = { 1, 4, 45, 6, 10, 8 };
int n = 16;
int arr_size = sizeof(A) / sizeof(A[0]);
// Function calling
printPairs(A, arr_size, n);
return 0;
}
C
// C program to check if given array
// has 2 elements whose sum is equal
// to the given value
// Works only if range elements is limited
#include
#define MAX 100000
void printPairs(int arr[], int arr_size, int sum)
{
int i, temp;
/*initialize hash set as 0*/
bool s[MAX] = { 0 };
for (i = 0; i < arr_size; i++)
{
temp = sum - arr[i];
if (s[temp] == 1)
printf(
"Pair with given sum %d is (%d, %d) n",
sum, arr[i], temp);
s[arr[i]] = 1;
}
}
/* Driver Code */
int main()
{
int A[] = { 1, 4, 45, 6, 10, 8 };
int n = 16;
int arr_size = sizeof(A) / sizeof(A[0]);
printPairs(A, arr_size, n);
getchar();
return 0;
}
Java
// Java implementation using Hashing
import java.io.*;
import java.util.HashSet;
class PairSum {
static void printpairs(int arr[], int sum)
{
HashSet s = new HashSet();
for (int i = 0; i < arr.length; ++i)
{
int temp = sum - arr[i];
// checking for condition
if (s.contains(temp)) {
System.out.println(
"Pair with given sum "
+ sum + " is (" + arr[i]
+ ", " + temp + ")");
}
s.add(arr[i]);
}
}
// Driver Code
public static void main(String[] args)
{
int A[] = { 1, 4, 45, 6, 10, 8 };
int n = 16;
printpairs(A, n);
}
}
// This article is contributed by Aakash Hasija
Python
# Python program to find if there are
# two elements wtih given sum
# function to check for the given sum
# in the array
def printPairs(arr, arr_size, sum):
# Create an empty hash set
s = set()
for i in range(0, arr_size):
temp = sum-arr[i]
if (temp in s):
print "Pair with given sum "+ str(sum) +
" is (" + str(arr[i]) + ", " + str(temp) + ")"
s.add(arr[i])
# driver code
A = [1, 4, 45, 6, 10, 8]
n = 16
printPairs(A, len(A), n)
# This code is contributed by __Devesh Agrawal__
C#
// C# implementation using Hashing
using System;
using System.Collections.Generic;
class GFG {
static void printpairs(int[] arr,
int sum)
{
HashSet s = new HashSet();
for (int i = 0; i < arr.Length; ++i)
{
int temp = sum - arr[i];
// checking for condition
if (s.Contains(temp)) {
Console.Write("Pair with given sum " +
sum + " is (" + arr[i] + ", " + temp + ")");
}
s.Add(arr[i]);
}
}
// Driver Code
static void Main()
{
int[] A = new int[] { 1, 4, 45,
6, 10, 8 };
int n = 16;
printpairs(A, n);
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
Javascript
C++
// Code in cpp to tell if there
// exists a pair in array whose
// sum results in x.
#include
using namespace std;
// Function to print pairs
void printPairs(int a[], int n, int x)
{
int i;
int rem[x];
for (i = 0; i < x; i++)
{
// initializing the rem
// values with 0's.
rem[i] = 0;
}
for (i = 0; i < n; i++)
{
if (a[i] < x)
{
// Perform the remainder
// operation only if the
// element is x, as numbers
// greater than x can't
// be used to get a sum x.
// Updating the count of remainders.
rem[a[i] % x]++;
}
}
// Traversing the remainder list
// from start to middle to
// find pairs
for (i = 1; i < x / 2; i++)
{
if (rem[i] > 0 && rem[x - i] > 0)
{
// The elements with remainders
// i and x-i will
// result to a sum of x.
// Once we get two
// elements which add up to x ,
// we print x and
// break.
cout << "Yes"
<< "\n";
break;
}
}
// Once we reach middle of
// remainder array, we have to
// do operations based on x.
if (i >= x / 2)
{
if (x % 2 == 0)
{
if (rem[x / 2] > 1)
{
// if x is even and
// we have more than 1
// elements with remainder
// x/2, then we will
// have two distinct elements
// which add up
// to x. if we dont have
//more than 1
// element, print "No".
cout << "Yes"
<< "\n";
}
else
{
cout << "No"
<< "\n";
}
}
else
{
// When x is odd we continue
// the same process
// which we did in previous loop.
if (rem[x / 2] > 0 &&
rem[x - x / 2] > 0)
{
cout << "Yes"
<< "\n";
}
else
{
cout << "No"
<< "\n";
}
}
}
}
/* Driver Code */
int main()
{
int A[] = { 1, 4, 45, 6, 10, 8 };
int n = 16;
int arr_size = sizeof(A) / sizeof(A[0]);
// Function calling
printPairs(A, arr_size, n);
return 0;
}
// This article is contributed by Sai Sanjana Gudla
Java
// Code in Java to tell if there
// exists a pair in array whose
// sum results in x.
import java.util.*;
class GFG{
// Function to print pairs
static void printPairs(int a[], int n, int x)
{
int i;
int []rem = new int[x];
for (i = 0; i < x; i++)
{
// initializing the rem
// values with 0's.
rem[i] = 0;
}
for (i = 0; i < n; i++)
{
if (a[i] < x)
{
// Perform the remainder
// operation only if the
// element is x, as numbers
// greater than x can't
// be used to get a sum x.
// Updating the count of remainders.
rem[a[i] % x]++;
}
}
// Traversing the remainder list
// from start to middle to
// find pairs
for (i = 1; i < x / 2; i++)
{
if (rem[i] > 0 && rem[x - i] > 0)
{
// The elements with remainders
// i and x-i will
// result to a sum of x.
// Once we get two
// elements which add up to x ,
// we print x and
// break.
System.out.print("Yes"
+ "\n");
break;
}
}
// Once we reach middle of
// remainder array, we have to
// do operations based on x.
if (i >= x / 2)
{
if (x % 2 == 0)
{
if (rem[x / 2] > 1)
{
// if x is even and
// we have more than 1
// elements with remainder
// x/2, then we will
// have two distinct elements
// which add up
// to x. if we dont have
//more than 1
// element, print "No".
System.out.print("Yes"
+ "\n");
}
else
{
System.out.print("No"
+ "\n");
}
}
else
{
// When x is odd we continue
// the same process
// which we did in previous loop.
if (rem[x / 2] > 0 &&
rem[x - x / 2] > 0)
{
System.out.print("Yes"
+ "\n");
}
else
{
System.out.print("No"
+ "\n");
}
}
}
}
/* Driver Code */
public static void main(String[] args)
{
int A[] = { 1, 4, 45, 6, 10, 8 };
int n = 16;
int arr_size = A.length;
// Function calling
printPairs(A, arr_size, n);
}
}
// This code is contributed by aashish1995
Python3
# Code in Python3 to tell if there
# exists a pair in array whose
# sum results in x.
# Function to print pairs
def printPairs(a, n, x):
rem = []
for i in range(x):
# Initializing the rem
# values with 0's.
rem.append(0)
for i in range(n):
if (a[i] < x):
# Perform the remainder operation
# only if the element is x, as
# numbers greater than x can't
# be used to get a sum x.Updating
# the count of remainders.
rem[a[i] % x] += 1
# Traversing the remainder list from
# start to middle to find pairs
for i in range(1, x // 2):
if (rem[i] > 0 and rem[x - i] > 0):
# The elements with remainders
# i and x-i will result to a
# sum of x. Once we get two
# elements which add up to x,
# we print x and break.
print("Yes")
break
# Once we reach middle of
# remainder array, we have to
# do operations based on x.
if (i >= x // 2):
if (x % 2 == 0):
if (rem[x // 2] > 1):
# If x is even and we have more
# than 1 elements with remainder
# x/2, then we will have two
# distinct elements which add up
# to x. if we dont have than 1
# element, print "No".
print("Yes")
else:
print("No")
else:
# When x is odd we continue
# the same process which we
# did in previous loop.
if (rem[x // 2] > 0 and
rem[x - x // 2] > 0):
print("Yes")
else:
print("No")
# Driver Code
A = [ 1, 4, 45, 6, 10, 8 ]
n = 16
arr_size = len(A)
# Function calling
printPairs(A, arr_size, n)
# This code is contributed by subhammahato348
C#
// C# Code in C# to tell if there
// exists a pair in array whose
// sum results in x.
using System;
class GFG
{
// Function to print pairs
static void printPairs(int []a, int n, int x)
{
int i;
int []rem = new int[x];
for (i = 0; i < x; i++)
{
// initializing the rem
// values with 0's.
rem[i] = 0;
}
for (i = 0; i < n; i++)
{
if (a[i] < x)
{
// Perform the remainder
// operation only if the
// element is x, as numbers
// greater than x can't
// be used to get a sum x.
// Updating the count of remainders.
rem[a[i] % x]++;
}
}
// Traversing the remainder list
// from start to middle to
// find pairs
for (i = 1; i < x / 2; i++)
{
if (rem[i] > 0 && rem[x - i] > 0)
{
// The elements with remainders
// i and x-i will
// result to a sum of x.
// Once we get two
// elements which add up to x ,
// we print x and
// break.
Console.Write("Yes" + "\n");
break;
}
}
// Once we reach middle of
// remainder array, we have to
// do operations based on x.
if (i >= x / 2)
{
if (x % 2 == 0)
{
if (rem[x / 2] > 1)
{
// if x is even and
// we have more than 1
// elements with remainder
// x/2, then we will
// have two distinct elements
// which add up
// to x. if we dont have
//more than 1
// element, print "No".
Console.Write("Yes" + "\n");
}
else
{
Console.Write("No"
+ "\n");
}
}
else
{
// When x is odd we continue
// the same process
// which we did in previous loop.
if (rem[x / 2] > 0 &&
rem[x - x / 2] > 0)
{
Console.Write("Yes"
+ "\n");
}
else
{
Console.WriteLine("No"
+ "\n");
}
}
}
}
/* Driver Code */
public static void Main(string[] args)
{
int[] A = { 1, 4, 45, 6, 10, 8 };
int n = 16;
int arr_size = A.Length;
// Function calling
printPairs(A, arr_size, n);
}
}
// This code is contributed by SoumikMondal
Javascript
输出:
Array has two elements with the given sum
复杂度分析:
- 时间复杂度:取决于我们使用的排序算法。
- 如果使用合并排序或堆排序,则在最坏的情况下使用 (-)(nlogn)。
- 如果使用快速排序,则在最坏的情况下为 O(n^2)。
- 辅助空间:这也取决于排序算法。合并排序的辅助空间是 O(n),堆排序的辅助空间是 O(1)。
方法2 :散列。
方法:这个问题可以通过使用散列技术有效地解决。使用hash_map检查当前数组值x(let) ,如果存在一个值target_sum-x ,该值添加到前者后给出target_sum 。这可以在恒定时间内完成。让我们看看下面的例子。
arr[] = {0, -1, 2, -3, 1}
sum = -2
Now start traversing:
Step 1: For ‘0’ there is no valid number ‘-2’ so store ‘0’ in hash_map.
Step 2: For ‘-1’ there is no valid number ‘-1’ so store ‘-1’ in hash_map.
Step 3: For ‘2’ there is no valid number ‘-4’ so store ‘2’ in hash_map.
Step 4: For ‘-3’ there is no valid number ‘1’ so store ‘-3’ in hash_map.
Step 5: For ‘1’ there is a valid number ‘-3’ so answer is 1, -3
算法:
- 初始化一个空的哈希表 s。
- 对 A[] 中的每个元素 A[i] 执行以下操作
- 如果设置了 s[x – A[i]],则打印对 (A[i], x – A[i])
- 将 A[i] 插入 s。
伪代码:
unordered_set s
for(i=0 to end)
if(s.find(target_sum - arr[i]) == s.end)
insert(arr[i] into s)
else
print arr[i], target-arr[i]
C++
// C++ program to check if given array
// has 2 elements whose sum is equal
// to the given value
#include
using namespace std;
void printPairs(int arr[], int arr_size, int sum)
{
unordered_set s;
for (int i = 0; i < arr_size; i++)
{
int temp = sum - arr[i];
if (s.find(temp) != s.end())
cout << "Pair with given sum "
<< sum << " is (" << arr[i] << ","
<< temp << ")" << endl;
s.insert(arr[i]);
}
}
/* Driver Code */
int main()
{
int A[] = { 1, 4, 45, 6, 10, 8 };
int n = 16;
int arr_size = sizeof(A) / sizeof(A[0]);
// Function calling
printPairs(A, arr_size, n);
return 0;
}
C
// C program to check if given array
// has 2 elements whose sum is equal
// to the given value
// Works only if range elements is limited
#include
#define MAX 100000
void printPairs(int arr[], int arr_size, int sum)
{
int i, temp;
/*initialize hash set as 0*/
bool s[MAX] = { 0 };
for (i = 0; i < arr_size; i++)
{
temp = sum - arr[i];
if (s[temp] == 1)
printf(
"Pair with given sum %d is (%d, %d) n",
sum, arr[i], temp);
s[arr[i]] = 1;
}
}
/* Driver Code */
int main()
{
int A[] = { 1, 4, 45, 6, 10, 8 };
int n = 16;
int arr_size = sizeof(A) / sizeof(A[0]);
printPairs(A, arr_size, n);
getchar();
return 0;
}
Java
// Java implementation using Hashing
import java.io.*;
import java.util.HashSet;
class PairSum {
static void printpairs(int arr[], int sum)
{
HashSet s = new HashSet();
for (int i = 0; i < arr.length; ++i)
{
int temp = sum - arr[i];
// checking for condition
if (s.contains(temp)) {
System.out.println(
"Pair with given sum "
+ sum + " is (" + arr[i]
+ ", " + temp + ")");
}
s.add(arr[i]);
}
}
// Driver Code
public static void main(String[] args)
{
int A[] = { 1, 4, 45, 6, 10, 8 };
int n = 16;
printpairs(A, n);
}
}
// This article is contributed by Aakash Hasija
Python
# Python program to find if there are
# two elements wtih given sum
# function to check for the given sum
# in the array
def printPairs(arr, arr_size, sum):
# Create an empty hash set
s = set()
for i in range(0, arr_size):
temp = sum-arr[i]
if (temp in s):
print "Pair with given sum "+ str(sum) +
" is (" + str(arr[i]) + ", " + str(temp) + ")"
s.add(arr[i])
# driver code
A = [1, 4, 45, 6, 10, 8]
n = 16
printPairs(A, len(A), n)
# This code is contributed by __Devesh Agrawal__
C#
// C# implementation using Hashing
using System;
using System.Collections.Generic;
class GFG {
static void printpairs(int[] arr,
int sum)
{
HashSet s = new HashSet();
for (int i = 0; i < arr.Length; ++i)
{
int temp = sum - arr[i];
// checking for condition
if (s.Contains(temp)) {
Console.Write("Pair with given sum " +
sum + " is (" + arr[i] + ", " + temp + ")");
}
s.Add(arr[i]);
}
}
// Driver Code
static void Main()
{
int[] A = new int[] { 1, 4, 45,
6, 10, 8 };
int n = 16;
printpairs(A, n);
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
Javascript
输出:
Pair with given sum 16 is (10, 6)
复杂度分析:
- 时间复杂度: O(n)。
因为整个数组只需要遍历一次。 - 辅助空间: O(n)。
哈希映射已用于存储数组元素。
注意:如果数字范围包含负数,那么它也可以正常工作。
方法 3 :使用小于 x 的元素的余数。
方法:
这个想法是计算除以 x 时有余数的元素,即0 到 x-1 ,每个余数分开。假设我们有x 为 6 ,那么小于 6 且余数加起来为 6 的数字相加时的总和为 6。例如,我们有元素,数组中的 2,4 和 2%6 = 2 和 4%6 =4,这些余数加起来是 6。像这样,我们必须检查有余数 (1,5) 的对,(2,4),(3,3)。如果我们有一个或多个余数为 1 的元素和一个或多个余数为 5 的元素,那么我们肯定会得到一个总和为 6。这里我们不考虑 (0,6),因为结果对的元素应该小于 6 . 当涉及到 (3,3) 时,我们必须检查是否有两个元素的余数为 3,然后我们可以说“存在一对总和为 x”。
算法:
1. 创建一个大小为 x 的数组。
2. 将所有 rem 元素初始化为零。
3.遍历给定数组
- 如果 arr[i] 小于 x,请执行以下操作:
- r=arr[i]%x 这样做是为了得到余数。
- rem[r]=rem[r]+1 即增加与 x 相除时余数为 r 的元素的数量。
4. 现在,从 1 到 x/2 遍历 rem 数组。
- If(rem[i]> 0 and rem[xi]>0) 然后打印“YES”并退出循环。这意味着我们有一对在执行时导致 x 。
5. 现在当我们到达上述循环中的 x/2 时
- 如果 x 是偶数,为了得到一对,我们应该有两个余数为 x/2 的元素。
- 如果 rem[x/2]>1 则打印“YES”否则打印“NO”
- 如果不满足 x 是奇数,它将与 xx/2 有一个单独的对。
- 如果 rem[x/2]>1 且 rem[xx/2]>1 ,则打印“Yes”,否则打印“No”;
上述算法的执行情况:
C++
// Code in cpp to tell if there
// exists a pair in array whose
// sum results in x.
#include
using namespace std;
// Function to print pairs
void printPairs(int a[], int n, int x)
{
int i;
int rem[x];
for (i = 0; i < x; i++)
{
// initializing the rem
// values with 0's.
rem[i] = 0;
}
for (i = 0; i < n; i++)
{
if (a[i] < x)
{
// Perform the remainder
// operation only if the
// element is x, as numbers
// greater than x can't
// be used to get a sum x.
// Updating the count of remainders.
rem[a[i] % x]++;
}
}
// Traversing the remainder list
// from start to middle to
// find pairs
for (i = 1; i < x / 2; i++)
{
if (rem[i] > 0 && rem[x - i] > 0)
{
// The elements with remainders
// i and x-i will
// result to a sum of x.
// Once we get two
// elements which add up to x ,
// we print x and
// break.
cout << "Yes"
<< "\n";
break;
}
}
// Once we reach middle of
// remainder array, we have to
// do operations based on x.
if (i >= x / 2)
{
if (x % 2 == 0)
{
if (rem[x / 2] > 1)
{
// if x is even and
// we have more than 1
// elements with remainder
// x/2, then we will
// have two distinct elements
// which add up
// to x. if we dont have
//more than 1
// element, print "No".
cout << "Yes"
<< "\n";
}
else
{
cout << "No"
<< "\n";
}
}
else
{
// When x is odd we continue
// the same process
// which we did in previous loop.
if (rem[x / 2] > 0 &&
rem[x - x / 2] > 0)
{
cout << "Yes"
<< "\n";
}
else
{
cout << "No"
<< "\n";
}
}
}
}
/* Driver Code */
int main()
{
int A[] = { 1, 4, 45, 6, 10, 8 };
int n = 16;
int arr_size = sizeof(A) / sizeof(A[0]);
// Function calling
printPairs(A, arr_size, n);
return 0;
}
// This article is contributed by Sai Sanjana Gudla
Java
// Code in Java to tell if there
// exists a pair in array whose
// sum results in x.
import java.util.*;
class GFG{
// Function to print pairs
static void printPairs(int a[], int n, int x)
{
int i;
int []rem = new int[x];
for (i = 0; i < x; i++)
{
// initializing the rem
// values with 0's.
rem[i] = 0;
}
for (i = 0; i < n; i++)
{
if (a[i] < x)
{
// Perform the remainder
// operation only if the
// element is x, as numbers
// greater than x can't
// be used to get a sum x.
// Updating the count of remainders.
rem[a[i] % x]++;
}
}
// Traversing the remainder list
// from start to middle to
// find pairs
for (i = 1; i < x / 2; i++)
{
if (rem[i] > 0 && rem[x - i] > 0)
{
// The elements with remainders
// i and x-i will
// result to a sum of x.
// Once we get two
// elements which add up to x ,
// we print x and
// break.
System.out.print("Yes"
+ "\n");
break;
}
}
// Once we reach middle of
// remainder array, we have to
// do operations based on x.
if (i >= x / 2)
{
if (x % 2 == 0)
{
if (rem[x / 2] > 1)
{
// if x is even and
// we have more than 1
// elements with remainder
// x/2, then we will
// have two distinct elements
// which add up
// to x. if we dont have
//more than 1
// element, print "No".
System.out.print("Yes"
+ "\n");
}
else
{
System.out.print("No"
+ "\n");
}
}
else
{
// When x is odd we continue
// the same process
// which we did in previous loop.
if (rem[x / 2] > 0 &&
rem[x - x / 2] > 0)
{
System.out.print("Yes"
+ "\n");
}
else
{
System.out.print("No"
+ "\n");
}
}
}
}
/* Driver Code */
public static void main(String[] args)
{
int A[] = { 1, 4, 45, 6, 10, 8 };
int n = 16;
int arr_size = A.length;
// Function calling
printPairs(A, arr_size, n);
}
}
// This code is contributed by aashish1995
蟒蛇3
# Code in Python3 to tell if there
# exists a pair in array whose
# sum results in x.
# Function to print pairs
def printPairs(a, n, x):
rem = []
for i in range(x):
# Initializing the rem
# values with 0's.
rem.append(0)
for i in range(n):
if (a[i] < x):
# Perform the remainder operation
# only if the element is x, as
# numbers greater than x can't
# be used to get a sum x.Updating
# the count of remainders.
rem[a[i] % x] += 1
# Traversing the remainder list from
# start to middle to find pairs
for i in range(1, x // 2):
if (rem[i] > 0 and rem[x - i] > 0):
# The elements with remainders
# i and x-i will result to a
# sum of x. Once we get two
# elements which add up to x,
# we print x and break.
print("Yes")
break
# Once we reach middle of
# remainder array, we have to
# do operations based on x.
if (i >= x // 2):
if (x % 2 == 0):
if (rem[x // 2] > 1):
# If x is even and we have more
# than 1 elements with remainder
# x/2, then we will have two
# distinct elements which add up
# to x. if we dont have than 1
# element, print "No".
print("Yes")
else:
print("No")
else:
# When x is odd we continue
# the same process which we
# did in previous loop.
if (rem[x // 2] > 0 and
rem[x - x // 2] > 0):
print("Yes")
else:
print("No")
# Driver Code
A = [ 1, 4, 45, 6, 10, 8 ]
n = 16
arr_size = len(A)
# Function calling
printPairs(A, arr_size, n)
# This code is contributed by subhammahato348
C#
// C# Code in C# to tell if there
// exists a pair in array whose
// sum results in x.
using System;
class GFG
{
// Function to print pairs
static void printPairs(int []a, int n, int x)
{
int i;
int []rem = new int[x];
for (i = 0; i < x; i++)
{
// initializing the rem
// values with 0's.
rem[i] = 0;
}
for (i = 0; i < n; i++)
{
if (a[i] < x)
{
// Perform the remainder
// operation only if the
// element is x, as numbers
// greater than x can't
// be used to get a sum x.
// Updating the count of remainders.
rem[a[i] % x]++;
}
}
// Traversing the remainder list
// from start to middle to
// find pairs
for (i = 1; i < x / 2; i++)
{
if (rem[i] > 0 && rem[x - i] > 0)
{
// The elements with remainders
// i and x-i will
// result to a sum of x.
// Once we get two
// elements which add up to x ,
// we print x and
// break.
Console.Write("Yes" + "\n");
break;
}
}
// Once we reach middle of
// remainder array, we have to
// do operations based on x.
if (i >= x / 2)
{
if (x % 2 == 0)
{
if (rem[x / 2] > 1)
{
// if x is even and
// we have more than 1
// elements with remainder
// x/2, then we will
// have two distinct elements
// which add up
// to x. if we dont have
//more than 1
// element, print "No".
Console.Write("Yes" + "\n");
}
else
{
Console.Write("No"
+ "\n");
}
}
else
{
// When x is odd we continue
// the same process
// which we did in previous loop.
if (rem[x / 2] > 0 &&
rem[x - x / 2] > 0)
{
Console.Write("Yes"
+ "\n");
}
else
{
Console.WriteLine("No"
+ "\n");
}
}
}
}
/* Driver Code */
public static void Main(string[] args)
{
int[] A = { 1, 4, 45, 6, 10, 8 };
int n = 16;
int arr_size = A.Length;
// Function calling
printPairs(A, arr_size, n);
}
}
// This code is contributed by SoumikMondal
Javascript
Yes
时间复杂度: O(n+x)
辅助空间: O(x)
相关问题:
- 给定两个未排序的数组,找出总和为 x 的所有对
- 计算给定总和的对
- 计算差异等于 k 的所有不同对
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。