My current code is as follows. I think I was supposed to tweak the conditions under my for-loops (like I need to watch out how big the last number on the array is etc). Here my head started spinning. Any hints much appreciated:
public class Solution {
public IList<IList<int>> ThreeSum(int[] nums) {
var res = new List<IList<int>>();
Array.Sort(nums);
for(var i = 0; i < nums.Length; i++){
for(var j = 0; j < nums.Length; j++){
for(var k = 0; k < nums.Length; k++){
if(j != k && i != j && i != k){
res.Add(new List<int>(){nums[i], nums[j], nums[k]});
}
}
}
}
return res;
}
}
Hello, @awkwineh183. Sorry for the slow reply. Seeing your post, I decided to attempt this myself. It proved to be much more challenging than I anticipated. Looking at what you have so far, your code returns a list of every possible combination of 3 values that have unique indices. You only want those that have a sum of 0. You also can’t have duplicates in your returned list. [-1, 0, 1] and [0, 1, -1] are considered duplicates in this challenge. You could alter your code a bit, and only add lists of numbers that have a sum of 0, but you need to come up with a way to avoid returning duplicates. Then you’ll need to work on optimizing the code in order to pass all of the tests in the time allotted. Good luck!
I think I need to do something about this line if((nums[j] != nums[k] && nums[i] != nums[j] && nums[i] != nums[k]) && (nums[i] + nums[j] + nums[k] == 0)){ This is more like a dirty code I guess.
Maybe do you have any suggestion/links so I can get some hints to clean up this code?
j, k, and i should not be equal, but the ints in nums at those indices can be. [0, 0, 0] and [-1, -1, 2] would be acceptable results if the input were { -1, -1, 0, 0, 0, 2 } for example.
You have to keep duplicates out of your result list. They consider a list with the same three integers in any order to be duplicates, so [-1, 2, -1] and [-1, -1, 2] are duplicates.