611 Valid Triangle Number

1. Question

Given an array consists of non-negative integers, your task is to count the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.
Example 1:
1
Input: [2,2,3,4]
2
3
Output: 3
4
5
Explanation:
6
Valid combinations are:
7
2,3,4 (using the first 2)
8
2,3,4 (using the second 2)
9
2,2,3
Copied!

2. Implementation

(1) Two Pointer
1
class Solution {
2
public int triangleNumber(int[] nums) {
3
if (nums == null || nums.length <= 2) {
4
return 0;
5
}
6
7
Arrays.sort(nums);
8
int count = 0;
9
10
for (int i = 0; i < nums.length - 2; i++) {
11
int k = i + 2;
12
for (int j = i + 1; nums[i] != 0 && j < nums.length - 1; j++) {
13
while (k < nums.length && nums[i] + nums[j] > nums[k]) {
14
k++;
15
}
16
count += k - j - 1;
17
}
18
}
19
return count;
20
}
21
}
Copied!

3. Time & Space Complexity

Two Pointer: 时间复杂度O(n^2), 空间复杂度O(1),因为sorting需要空间