-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathsolution.java
More file actions
22 lines (21 loc) · 760 Bytes
/
Copy pathsolution.java
File metadata and controls
22 lines (21 loc) · 760 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Arrays;
class Solution {
public int triangleNumber(int[] nums) {
int n = nums.length;
if (n < 3) return 0;
Arrays.sort(nums); // sort ascending
int count = 0;
for (int k = n - 1; k >= 2; k--) {
int i = 0, j = k - 1; // two pointers
while (i < j) {
if (nums[i] + nums[j] > nums[k]) {
count += j - i; // all between i and j-1 pair with j
j--; // decrease b
} else {
i++; // increase a
}
}
}
return count;
}
}