JAVA Solution O(n2)


  • 0
    Y
    public class Solution {
        public int threeSumSmaller(int[] nums, int target) {
            int res = 0;
            Arrays.sort(nums);
            for(int i = 0; i < nums.length; i++) {
                int left = i + 1;
                int right = nums.length - 1;
                while(left < right) {
                    int sum = nums[i] + nums[left] + nums[right];
                    if(sum < target) {
                        res += right - left;
                        left++;
                    }else if(sum >= target) {
                        right--;
                    }
                }
            }
            
            return res;
        }
    }

Log in to reply
 

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