help to avoid duplicates


  • 0
    Y

    Can anyone make some modification to help avoid duplicates based on my code?

    """public static List<List<Integer>> threeSum(int[] nums) {
    List<List<Integer>> flist = new ArrayList<List<Integer>>();

    	Arrays.sort(nums);
    	for (int i = 0; i < nums.length; i++) {
    		int[] subarray = Arrays.copyOfRange(nums, i + 1, nums.length);
    		int[] arr = twoSum(subarray, -nums[i]);
    		if (arr != null) {
    			List<Integer> list = new ArrayList<Integer>();
    			list.add(nums[i]);
    			list.add(arr[0]);
    			list.add(arr[1]);
    			flist.add(list);
    		}		
    	}		
    	return flist;
    }
    
    public static int[] twoSum(int[] nums, int target) {
    	int low = 0;
    	int high = nums.length - 1;
    	int[] result = new int[2];
    	while (low < high) {
    		if (nums[low] + nums[high] < target) {
    			low++;
    		} else if (nums[low] + nums[high] > target) {
    			high--;
    		} else {
    			result[0] = nums[low];
    			result[1] = nums[high];
    			return result;
    		}
    	}
    	return null;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.