Triangle
来源:互联网 发布:终端网络管理软件 编辑:程序博客网 时间:2024/06/05 16:03
A zero-indexed array A consisting of N integers is given. A triplet (P, Q, R) is triangular if 0 ≤ P < Q < R < N and:
A[P] + A[Q] > A[R],
A[Q] + A[R] > A[P],
A[R] + A[P] > A[Q].
For example, consider array A such that:
A[0] = 10 A[1] = 2 A[2] = 5
A[3] = 1 A[4] = 8 A[5] = 20
Triplet (0, 2, 4) is triangular.
Write a function:
class Solution { public int solution(int[] A); }
that, given a zero-indexed array A consisting of N integers, returns 1 if there exists a triangular triplet for this array and returns 0 otherwise.
For example, given array A such that:
A[0] = 10 A[1] = 2 A[2] = 5
A[3] = 1 A[4] = 8 A[5] = 20
the function should return 1, as explained above. Given array A such that:
A[0] = 10 A[1] = 50 A[2] = 5
A[3] = 1
the function should return 0.
Assume that:
N is an integer within the range [0..100,000];
each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].
Complexity:
expected worst-case time complexity is O(N*log(N));
expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
解答。
因为有 O(N*log(N))的要求,一般就要先sort一下。
sort 之后是从小到大的,除非reverse = True
然后我们就要到sorted array里面找到all possible i
import java.util.*;class Solution { public int solution(int[] A) { Arrays.sort(A); for(int i = 0; i< A.length-2; i++){ if(A[i] > A[i+2] - A[i+1]){//use subtraction to avoid overflow return 1; } } return 0; }}
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- Triangle
- 从头认识java-10.4 捕获所有异常
- Android asset raw 文件夹的区别深入解析
- 黑马程序员--如何使用API
- crfsuite 安装文档
- OC第一天
- Triangle
- android studio工程目录
- Android中防止重复点击的小技巧
- 【程序设计基础_C语言】北理工的恶龙
- Kd-Tree算法
- iOS UIWebView与JS交互
- 汇编语言程序开发过程
- zstack的层次结构
- 煎饼(Stacks of Flapjacks,UVa 120)