Java Two method, both O(n^2)


  • 0
    public int threeSumSmaller(int[] nums, int target) {
            if (nums.length < 3) return 0;
            Arrays.sort(nums);
            int count = 0;
            for (int i = 0; i < nums.length; i++) {
                int j = i + 1, k = nums.length - 1;
                while (k > i + 1) {
                    while (j < k && nums[i] + nums[j] + nums[k] < target) j++;
                    count += Math.min(k - i - 1, j - i - 1);
                    k--;
                }
            }
            return count;
        }
    
    public int threeSumSmaller(int[] nums, int target) {
            if (nums.length < 3) return 0;
            Arrays.sort(nums);
            int count = 0;
            for (int i = 0; i < nums.length; i++) {
                int j = i+1, k = nums.length-1;
                while (j < k) {
                    if (nums[i] + nums[j] + nums[k] < target) {
                        count += k-j;
                        j++;
                    } else k--;
                }
            }
            return count;
        }
    

Log in to reply
 

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