Last active
April 13, 2016 14:47
-
-
Save cangoal/efd91353e12bf915ab9f034ed78b2353 to your computer and use it in GitHub Desktop.
LeetCode - 3Sum Smaller
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target. | |
| // For example, given nums = [-2, 0, 1, 3], and target = 2. | |
| // Return 2. Because there are two triplets which sums are less than 2: | |
| // [-2, 0, 1] | |
| // [-2, 0, 3] | |
| // Follow up: | |
| // Could you solve it in O(n2) runtime? | |
| public int threeSumSmaller(int[] nums, int target) { | |
| int res = 0; | |
| if(nums == null || nums.length < 3) return res; | |
| Arrays.sort(nums); | |
| for(int i = nums.length - 1; i >= 2; i--){ | |
| int left = 0, right = i - 1; | |
| while(left < right){ | |
| if(nums[left] + nums[right] + nums[i] >= target){ | |
| right--; | |
| } else { | |
| res += right - left; | |
| left++; | |
| } | |
| } | |
| } | |
| return res; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment