Array

3Sum

Link: https://leetcode.com/problems/3sum/

Code:

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        for (int i = 0; i < nums.length && nums[i] <= 0; ++i) {
            if (i == 0 || nums[i-1] != nums[i]) {
                twoSumII(i, nums, res);
            }
        }
        return res;
    }
    
    void twoSumII(int i, int[] nums, List<List<Integer>> res) {
        int low = i + 1, high = nums.length - 1;
        while (low < high) {
            int sum = nums[i] + nums[low] + nums[high];
            if ( sum > 0) {
                --high;
            } else if (sum < 0) {
                ++low;
            } else {
                res.add(Arrays.asList(nums[i], nums[low++], nums[high--]));
                while (low < high && nums[low] == nums[low - 1]) {
                    ++low;
                } 
            }
        }
    }
}
  • Time complexity: O(n^2);

  • Sort the array first (Arrays.sort()) and then use two pointers to find the target.

  • Note how to create a new list in Java;

  • Note how to add a new element to a list in Java (res.add(...));

  • Note how to use Arrays.asList() to create a list from an array;

  • Difference of post-increment and pre-increment (++i and i++);

  • Difference between array and list in Java (List<Integer> and int[])?

3Sum Closest

Link: https://leetcode.com/problems/3sum-closest/

Code:

  • Time complexity: O(n^2);

  • Two pointers;

  • Integer.MAX_VALUE is the largest integer in Java;

  • Math.abs() is the absolute value of a number;

Product of Array Except Self

Link: https://leetcode.com/problems/product-of-array-except-self/

Code:

  • Time complexity: O(n);

  • Space complexity: O(n);

Kids With the Greatest Number of Candies

Link: https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/

Code:

  • Time complexity: O(n);

  • Space complexity: O(n).

Increasing Triplet Subsequence

Link: https://leetcode.com/problems/increasing-triplet-subsequence/

Code:

  • Time complexity: O(n);

  • Space complexity: O(1).

Last updated