Skip to content

Commit 03ac125

Browse files
committed
611. Valid Triangle Number
1 parent 1d2dd1e commit 03ac125

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
3+
1. 아이디어 : 삼각형을 만드는 조건은 a+b>c 이므로, 먼저 숫자를 정렬 뒤, 가장 큰 수 기준 투포인터를 활용하여 구한다.
4+
5+
2. 시간복잡도 : o(N^2)
6+
7+
3. 자료구조/알고리즘 : 투포인터, 정렬
8+
9+
*/
10+
11+
class Solution {
12+
public int triangleNumber(int[] nums) {
13+
// 삼각형을 만들 수 있는 모든 경우의 수
14+
// idx 기준
15+
16+
// a+b > c
17+
Arrays.sort(nums);
18+
int ans = 0;
19+
20+
// 2, 2, 3, 4
21+
for(int i=nums.length-1; i>1; i--) {
22+
int c = nums[i];
23+
24+
int l = 0;
25+
int r = i-1;
26+
27+
while(l<r) {
28+
if(nums[l] + nums[r] <= c) l++;
29+
else {
30+
ans+=r-l;
31+
r--;
32+
}
33+
}
34+
}
35+
36+
return ans;
37+
38+
}
39+
}

0 commit comments

Comments
 (0)