Codility经典算法题之十五:Triangle

  • Post author:
  • Post category:其他


Task description:

An 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 an 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).


Solution:

题目是检查一个数组是否存在可以组成三角形的元素,思路先把列表排序,检查所有相邻的三个值,x,y,z因为肯定存在x+z>y,y+z>x,所以只要检查x+y>z就可以确认存在了

def solution(p):

s = sorted(p)

lenp = len(p)

for i in range(lenp-2):

if s[i]+s[i+1]>s[i+2]:

return 1

return 0

读后有收获可以微信请作者吃棒棒糖哦~ ,有任何问题评论留言我会回复哒。



版权声明:本文为u010184335原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。