DEV Community

Cover image for Array- Q4 3Sum
Pranjal Sailwal
Pranjal Sailwal

Posted on โ€ข Edited on

Array- Q4 3Sum

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> output = new ArrayList<>();
        for (int i = 0; i < nums.length - 2; i++) {
            if (i == 0 || (i > 0 && nums[i] != nums[i - 1])) {
                int target = -nums[i];
                int j = i + 1;
                int k = nums.length - 1;
                while (j < k) {
                    int sum = nums[j] + nums[k];
                    if (sum == target) {
                        output.add(Arrays.asList(nums[i], nums[j], nums[k]));
                        while (j < k && nums[j] == nums[j + 1]) j++;
                        while (j < k && nums[k] == nums[k - 1]) k--;
                        j++;
                        k--;
                    } else if (sum < target) {
                        j++;
                    } else {
                        k--;
                    }
                }
            }
        }
        return output;
    }
}
Enter fullscreen mode Exit fullscreen mode

๐—ข๐—ฝ๐—ฒ๐—ป ๐˜๐—ผ ๐˜‚๐—ฝ๐—ฑ๐—ฎ๐˜๐—ฒ๐˜€ ๐—ฎ๐—ป๐—ฑ ๐˜€๐˜‚๐—ด๐—ด๐—ฒ๐˜€๐˜๐—ถ๐—ผ๐—ป๐˜€.

Image of Timescale

๐Ÿš€ pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applicationsโ€”without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post โ†’

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

Retry later