Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

15. 3Sum #11

Open
Luchanaaaaa opened this issue Feb 15, 2023 · 0 comments
Open

15. 3Sum #11

Luchanaaaaa opened this issue Feb 15, 2023 · 0 comments
Labels

Comments

@Luchanaaaaa
Copy link
Owner

java

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> ans = new ArrayList<>();
        for(int i = 0; i < nums.length; i++){
            if(i > 0 && nums[i] == nums[i-1]) continue;
            int left = i + 1, right = nums.length - 1;
            int num1 = nums[i];

            while(left < right){
                int num2 = nums[left], num3 = nums[right];
                int sum = num1 + num2 + num3; 
                if(left -1 > i && nums[left -1] == nums[left]){
                    left++;
                    continue;
                }
                if(sum == 0) {
                    ans.add(Arrays.asList(num1, num2, num3));
                    left++;
                }
                else if(sum > 0) right--;
                else if(sum < 0) left++;
            }

        }
        return ans;

    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant