Question :
A balanced array is defined to be an array
where for every value n in the array, -n also is in the array. For example {-2,
3, 2, -3} is a balanced array. So is {-2, 2, 2, 2}. But {-5, 2, -2} is not
because 5 is not in the array.
Write a function named
isBalanced that returns 1 if its array argument is a balanced array. Otherwise
it returns 0.
If you are
programming in Java or C#, the function signature is
int isBalanced (int [ ] a);
If you are programming in C or
C++, the function signature is
int isBalanced(int a[ ], int
len) where len is the number of elements in the array.
Solution :
public static int
isBalanced(int [] a)
{
int
isBalanced = 1;
for(int i=0;i<a.Length;i++)
{
int isValid
= 0;
for(int j=0;j<a.Length;j++)
{
if(a[i]==-a[j])
{
isValid = 1;
break;
}
}
if
(isValid==0)
isBalanced = 0;
}
return isBalanced;
}
can we optimize it without using hashing?
ReplyDelete