- Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathValidTriangleNumber611.java
More file actions
Latest commit
108 lines (94 loc) · 3.01 KB
/
Copy pathValidTriangleNumber611.java
File metadata and controls
108 lines (94 loc) · 3.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/**
* 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:
* Input: [2,2,3,4]
* Output: 3
* Explanation:
* Valid combinations are:
* 2,3,4 (using the first 2)
* 2,3,4 (using the second 2)
* 2,2,3
*
* Note:
* The length of the given array won't exceed 1000.
* The integers in the given array are in the range of [0, 1000].
*/
publicclassValidTriangleNumber611 {
publicinttriangleNumber(int[] nums) {
if (nums == null || nums.length < 3) return0;
Arrays.sort(nums);
intres = 0;
for (inti=0; i<nums.length-2; i++) {
for (intj=i+1; j<nums.length-1; j++) {
for (intk=j+1; k<nums.length; k++) {
if (isValidTriangle(nums[i], nums[j], nums[k])) res++;
elsebreak;
}
}
}
returnres;
}
publicbooleanisValidTriangle(inta, intb, intc) {
if (a == 0 || b == 0 || c == 0) returnfalse;
intlongestSide = a;
if (b > longestSide) longestSide = b;
if (c > longestSide) longestSide = c;
returnlongestSide < (a + b + c - longestSide);
}
publicinttriangleNumber2(int[] nums) {
if (nums == null || nums.length < 3) return0;
Arrays.sort(nums);
int[] sum = newint[1001];
for(intn: nums) sum[n]++;
for(inti=1; i<1001; i++) sum[i] += sum[i-1];
intres = 0;
for (inti=0; i<nums.length-2; i++) {
if (nums[i] == 0) continue;
for (intj=i+1; j<nums.length-1; j++) {
if (nums[j] == 0) continue;
intupper = nums[i] + nums[j];
intlower = Math.abs(nums[i] - nums[j]);
intc = sum[upper-1] - Math.max(sum[lower], j+1);
res += c;
}
}
returnres;
}
/**
* https://leetcode.com/problems/valid-triangle-number/solution/
*/
publicinttriangleNumber3(int[] nums) {
intcount = 0;
Arrays.sort(nums);
for (inti = 0; i < nums.length - 2; i++) {
intk = i + 2;
for (intj = i + 1; j < nums.length - 1 && nums[i] != 0; j++) {
while (k < nums.length && nums[i] + nums[j] > nums[k])
k++;
count += k - j - 1;
}
}
returncount;
}
/**
* https://leetcode.com/problems/valid-triangle-number/discuss/104174/Java-O(n2)-Time-O(1)-Space
*/
publicstaticinttriangleNumber4(int[] A) {
Arrays.sort(A);
intcount = 0, n = A.length;
for (inti=n-1;i>=2;i--) {
intl = 0, r = i-1;
while (l < r) {
if (A[l] + A[r] > A[i]) {
count += r-l;
r--;
}
elsel++;
}
}
returncount;
}
}