Reputation: 23
I want to check an array, if the sum of three values from it is 0. One condition is that triplets are not allowed (0,0,0)
public static List<List<int>> ThreeSum(int[] num)
{
List<List<int>> returnList = new List<List<int>>();
for (int i = 0; i < num.Length; i++)
{
for (int j = 0; j < num.Length; j++)
{
for (int k = 0; k < num.Length; k++)
{
if (num[i] + num[j] + num[k] == 0 && num[i] <= num[j] && num[j] <= num[k] && (num[i] !=0 && num[j]!= 0 && num[k]!= 0))
{
List<int> listInt = new List<int>();
listInt.Add(num[i]);
listInt.Add(num[j]);
listInt.Add(num[k]);
if (!returnList.Contains(listInt))
{
returnList.Add(listInt);
}
}
}
}
}
return returnList;
}
this is the line im struggling with if (num[i] + num[j] + num[k] == 0 && num[i] <= num[j] && num[j] <= num[k] && (num[i] !=0 && num[j]!= 0 && num[k]!= 0))
So I'm tried a second bracket: (num[i] !=0 && num[j]!= 0 && num[k]!= 0)
to make sure that all these conditions need to be true at one time. As you might know this don't work out for me. Every zero is not allowed in the result but it should only prevent from tripple zeros.
One solution is : (-1, 0, 1) but I won't get it because my condition don't accept the zero in it.
Link to the problem(if interested) : https://leetcode.com/problems/3sum/
Upvotes: 1
Views: 68
Reputation: 29431
Your former condition was false; it meant i, j and k must all be different from 0. !(i == 0 || j == 0 || k == 0)
is what you want to do.
I would go with this:
public static List<List<int>> ThreeSum(int[] num)
{
List<List<int>> returnList = new List<List<int>>();
foreach (int i in num)
{
foreach (int j in num)
{
foreach (int k in num)
{
if (i + j + k == 0 && i <= j && j <= k && !(i == 0 || j == 0 || k == 0))
{
returnList.Add(new List<int> { i, j, k });
}
}
}
}
return returnList;
}
And if you're a bit masochist, with this:
public static List<List<int>> ThreeSum(int[] num)
{
List<List<int>> returnList = new List<List<int>>();
foreach (List<int> listInt in num.SelectMany(i => num.SelectMany(j => num.Where(k => i + j + k == 0 && i <= j && j <= k && !(i == 0 || j == 0 || k == 0)).Select(k => new List<int> {i, j, k}).Where(listInt => !returnList.Contains(listInt)))))
{
returnList.Add(listInt);
}
return returnList;
}
And by the way, check if the returnList contains a new list is useless since it'll always be false. (see edit on the first code, the second one can't be updated.)
Upvotes: 0
Reputation: 7884
Change
&& (num[i] !=0 && num[j]!= 0 && num[k]!= 0)
to:
&& !(num[i] == 0 && num[j] == 0 && num[k] == 0)
Upvotes: 0
Reputation: 2851
You should not be trying to check whether all of them are not equal to zero but rather checking if at least one of them is not equal to zero.
So instead of
(num[i] !=0 && num[j]!= 0 && num[k]!= 0)
do this check:
&& (num[i] !=0 || num[j]!= 0 || num[k]!= 0)
Upvotes: 1