Simple Java Solution


  • 0
    M
        public int threeSumSmaller(int[] nums, int target) {
            if (nums == null || nums.length < 3) return 0;
            int n = nums.length;
            Arrays.sort(nums);
            int cnt = 0;
            for (int k = 0; k < n - 2; ++k) {
                int i = k + 1, j = n - 1;
                int t = target - nums[k];
                while (i < j) {
                    if (nums[i] + nums[j] < t) {
                        cnt += j - i;
                        ++i;
                    } else {
                        --j;
                    }
                }
            }
            return cnt;
        }
    

Log in to reply
 

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