给定一个由N 个整数组成的数组arr[] ,任务是找到最大的数K ( > 0 ),使得值K和-K都出现在给定的数组arr[] 中。如果不存在这样的数字,则打印-1 。
例子:
Input: arr[] = {3, 2, -2, 5, -3}
Output: 3
Input: arr[] = {1, 2, 3, -4}
Output: -1
朴素方法:解决给定问题的最简单方法是迭代数组,对于每个元素,遍历剩余的数组以检查数组中是否存在其负值。完成数组遍历后,打印获得的最大此类数。
时间复杂度: O(N 2 )
辅助空间: O(1)
高效的方法:可以通过使用排序和两个指针来优化上述方法。请按照以下步骤解决此问题:
- 初始化一个变量,比如res为-1 ,它存储获得的最大元素。
- 对给定的数组arr[] 进行排序。
- 初始化两个变量,假设l和r为0和(N – 1) ,并执行以下步骤:
- 如果(arr[l] + arr[r]) 的值等于0 ,则返回arr[l]和arr[r]的绝对值。
- 否则,如果(arr[l] + arr[r]) 的值小于0 ,则 将l的值增加1 。
- 否则,将r的值减少1 。
- 完成上述步骤后,打印res的值作为结果。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the largest
// number k such that both k and
// -k are present in the array
int largestNum(vectorarr)
{
// Stores the resultant value
// of K
int res = 0;
// Sort the array arr[]
sort(arr.begin(), arr.end());
// Initialize two variables to
// use two pointers technique
int l = 0, r = arr.size() - 1;
// Iterate until the value of
// l is less than r
while (l < r)
{
// Find the value of the sum
int sum = arr[l] + arr[r];
// If the sum is 0, then the
// resultant element is found
if (sum == 0)
{
res = max(res, max(arr[l], arr[r]));
return res;
}
// If the sum is negative
else if (sum < 0)
{
l++;
}
// Otherwise, decrement r
else
{
r--;
}
}
return res;
}
// Driver Code
int main()
{
vectorarr = { 3, 2, -2, 5, -3 };
cout << (largestNum(arr));
}
// This code is contributed by amreshkumar3
Java
// Java program for the above approach
import java.io.*;
import java.util.*;
public class GFG {
// Function to find the largest
// number k such that both k and
// -k are present in the array
public static int largestNum(int[] arr)
{
// Stores the resultant value
// of K
int res = 0;
// Sort the array arr[]
Arrays.sort(arr);
// Initialize two variables to
// use two pointers technique
int l = 0, r = arr.length - 1;
// Iterate until the value of
// l is less than r
while (l < r) {
// Find the value of the sum
int sum = arr[l] + arr[r];
// If the sum is 0, then the
// resultant element is found
if (sum == 0) {
res = Math.max(
res, Math.max(
arr[l], arr[r]));
return res;
}
// If the sum is negative
else if (sum < 0) {
l++;
}
// Otherwise, decrement r
else {
r--;
}
}
return res;
}
// Driver Code
public static void main(String[] args)
{
int[] arr = { 3, 2, -2, 5, -3 };
System.out.println(
largestNum(arr));
}
}
Python3
# Python3 program for the above approach
# Function to find the largest
# number k such that both k and
# -k are present in the array
def largestNum(arr):
# Stores the resultant value
# of K
res = 0
# Sort the array arr[]
arr = sorted(arr)
# Initialize two variables to
# use two pointers technique
l = 0
r = len(arr) - 1
# Iterate until the value of
# l is less than r
while (l < r):
# Find the value of the sum
sum = arr[l] + arr[r]
# If the sum is 0, then the
# resultant element is found
if (sum == 0):
res = max(res, max(arr[l], arr[r]))
return res
# If the sum is negative
elif (sum < 0):
l += 1
# Otherwise, decrement r
else:
r-=1
return res
# Driver Code
if __name__ == '__main__':
arr =[3, 2, -2, 5, -3]
print(largestNum(arr))
# This code is contributed by mohit kumar 29.
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to find the largest
// number k such that both k and
// -k are present in the array
static int largestNum(Listarr)
{
// Stores the resultant value
// of K
int res = 0;
// Sort the array arr[]
arr.Sort();
// Initialize two variables to
// use two pointers technique
int l = 0, r = arr.Count - 1;
// Iterate until the value of
// l is less than r
while (l < r)
{
// Find the value of the sum
int sum = arr[l] + arr[r];
// If the sum is 0, then the
// resultant element is found
if (sum == 0)
{
res = Math.Max(res, Math.Max(arr[l],
arr[r]));
return res;
}
// If the sum is negative
else if (sum < 0)
{
l++;
}
// Otherwise, decrement r
else
{
r--;
}
}
return res;
}
// Driver Code
public static void Main()
{
Listarr = new List(){ 3, 2, -2, 5, -3 };
Console.Write(largestNum(arr));
}
}
// This code is contributed by bgangwar59
Javascript
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the largest
// number k such that both k and
// -k are present in the array
int largestNum(int arr[] ,int n)
{
// Stores the array elements
set st;
// Initialize a variable res as
// 0 to store maximum element
// while traversing the array
int res = 0;
// Iterate through array arr
for(int i = 0; i < n; i++)
{
// Add the current element
// into the st
st.insert(arr[i]);
// Check if the negative of
// this element is also
// present in the st or not
if (st.find(-1 * arr[i]) != st.end())
{
res = max(res, abs(arr[i]));
}
}
// Return the resultant element
return res;
}
// Drive Code
int main()
{
int arr[] = { 3, 2, -2, 5, -3 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << largestNum(arr, n);
}
// This code is contributed by SURENDRA_GANGWAR
Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG {
// Function to find the largest
// number k such that both k and
// -k are present in the array
public static int largestNum(int[] arr)
{
// Stores the array elements
Set set = new HashSet<>();
// Initialize a variable res as
// 0 to store maximum element
// while traversing the array
int res = 0;
// Iterate through array arr
for (int i = 0;
i < arr.length; i++) {
// Add the current element
// into the set
set.add(arr[i]);
// Check if the negative of
// this element is also
// present in the set or not
if (set.contains(-1 * arr[i])) {
res = Math.max(
res, Math.abs(arr[i]));
}
}
// Return the resultant element
return res;
}
// Drive Code
public static void
main(String[] args)
{
int[] arr = { 3, 2, -2, 5, -3 };
System.out.println(
largestNum(arr));
}
}
Python3
# Python3 program for the above approach
# Function to find the largest
# number k such that both k and
# -k are present in the array
def largestNum(arr, n) :
# Stores the array elements
st = set([])
# Initialize a variable res as
# 0 to store maximum element
# while traversing the array
res = 0
# Iterate through array arr
for i in range(n):
# Add the current element
# into the st
st.add(arr[i])
# Check if the negative of
# this element is also
# present in the st or not
if (-1 * arr[i]) in st:
res = max(res, abs(arr[i]))
# Return the resultant element
return res
arr = [ 3, 2, -2, 5, -3 ]
n = len(arr)
print(largestNum(arr, n))
# This code is contributed by divyeshrabadiya07
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
public class GFG{
// Function to find the largest
// number k such that both k and
// -k are present in the array
public static int largestNum(int[] arr)
{
// Stores the array elements
HashSet set = new HashSet();
// Initialize a variable res as
// 0 to store maximum element
// while traversing the array
int res = 0;
// Iterate through array arr
for (int i = 0;
i < arr.Length; i++) {
// Add the current element
// into the set
set.Add(arr[i]);
// Check if the negative of
// this element is also
// present in the set or not
if (set.Contains(-1 * arr[i])) {
res = Math.Max(
res, Math.Abs(arr[i]));
}
}
// Return the resultant element
return res;
}
// Drive Code
static public void Main (){
int[] arr = { 3, 2, -2, 5, -3 };
Console.WriteLine(
largestNum(arr));
}
}
// This code is contributed by unknown2108
Javascript
输出:
3
时间复杂度: O(N*log N)
辅助空间: O(1)
优化方法:可以通过将元素存储到 Set 中来进一步优化上述方法。请按照以下步骤解决此问题:
- 初始化一个存储数组元素的集合S。
- 初始化一个变量,比如res为-1以在遍历数组时存储最大元素。
- 使用变量i在范围[0, N – 1] 上迭代并执行以下步骤:
- 将当前元素添加到集合S 中。
- 如果该元素存在,则将res的值更新为当前元素。
- 完成上述步骤后,打印res的值作为结果。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the largest
// number k such that both k and
// -k are present in the array
int largestNum(int arr[] ,int n)
{
// Stores the array elements
set st;
// Initialize a variable res as
// 0 to store maximum element
// while traversing the array
int res = 0;
// Iterate through array arr
for(int i = 0; i < n; i++)
{
// Add the current element
// into the st
st.insert(arr[i]);
// Check if the negative of
// this element is also
// present in the st or not
if (st.find(-1 * arr[i]) != st.end())
{
res = max(res, abs(arr[i]));
}
}
// Return the resultant element
return res;
}
// Drive Code
int main()
{
int arr[] = { 3, 2, -2, 5, -3 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << largestNum(arr, n);
}
// This code is contributed by SURENDRA_GANGWAR
Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG {
// Function to find the largest
// number k such that both k and
// -k are present in the array
public static int largestNum(int[] arr)
{
// Stores the array elements
Set set = new HashSet<>();
// Initialize a variable res as
// 0 to store maximum element
// while traversing the array
int res = 0;
// Iterate through array arr
for (int i = 0;
i < arr.length; i++) {
// Add the current element
// into the set
set.add(arr[i]);
// Check if the negative of
// this element is also
// present in the set or not
if (set.contains(-1 * arr[i])) {
res = Math.max(
res, Math.abs(arr[i]));
}
}
// Return the resultant element
return res;
}
// Drive Code
public static void
main(String[] args)
{
int[] arr = { 3, 2, -2, 5, -3 };
System.out.println(
largestNum(arr));
}
}
蟒蛇3
# Python3 program for the above approach
# Function to find the largest
# number k such that both k and
# -k are present in the array
def largestNum(arr, n) :
# Stores the array elements
st = set([])
# Initialize a variable res as
# 0 to store maximum element
# while traversing the array
res = 0
# Iterate through array arr
for i in range(n):
# Add the current element
# into the st
st.add(arr[i])
# Check if the negative of
# this element is also
# present in the st or not
if (-1 * arr[i]) in st:
res = max(res, abs(arr[i]))
# Return the resultant element
return res
arr = [ 3, 2, -2, 5, -3 ]
n = len(arr)
print(largestNum(arr, n))
# This code is contributed by divyeshrabadiya07
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
public class GFG{
// Function to find the largest
// number k such that both k and
// -k are present in the array
public static int largestNum(int[] arr)
{
// Stores the array elements
HashSet set = new HashSet();
// Initialize a variable res as
// 0 to store maximum element
// while traversing the array
int res = 0;
// Iterate through array arr
for (int i = 0;
i < arr.Length; i++) {
// Add the current element
// into the set
set.Add(arr[i]);
// Check if the negative of
// this element is also
// present in the set or not
if (set.Contains(-1 * arr[i])) {
res = Math.Max(
res, Math.Abs(arr[i]));
}
}
// Return the resultant element
return res;
}
// Drive Code
static public void Main (){
int[] arr = { 3, 2, -2, 5, -3 };
Console.WriteLine(
largestNum(arr));
}
}
// This code is contributed by unknown2108
Javascript
输出:
3
时间复杂度: O(N)
辅助空间: O(N)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。