problem: given array s of n integers, there elements a, b, c in s such + b + c = 0? find unique triplets in array gives sum of zero.
to avoid duplicates use if-clause in while loop, , wondering why not work. thanks!
public list<list<integer>> threesum(int[] nums) { list<list<integer>> result = new arraylist<list<integer>>(); arrays.sort(nums); (int = 0; i<nums.length; i++){ if (i > 0 && nums[i] == nums[i-1]){ continue; } int target = -1*nums[i]; int start = i+1; int end = nums.length-1; while (start < end){ if (nums[start] == nums[start+1]){ start++; } if (nums[end] == nums[end--]){ end--; } if (nums[start]+nums[end] == target){ system.out.printf("found"); list<integer> temp = new arraylist<integer>(); temp.add(nums[i]); temp.add(nums[start]); temp.add(nums[end]); result.add(temp); start++; end--; } else if (nums[start]+nums[end] < target) { start++; } else { end--; } } } return result;
i testing on [-1,0,1] , code returned empty list. tried debug , printed messages, , seems when i=1, in while loop, first enters
if (nums[start] == nums[start+1]){ start++; }
but nums[start] not equal nums[start+1] when start=1. quite bizzare. can explain me?
replace string in code from
if (nums[end] == nums[end--]) {
to
if (nums[end] == nums[end - 1]) {
Comments
Post a Comment