룬아님의 취중코딩

Codility 16번 Triangle 본문

개발/알고리즘

Codility 16번 Triangle

룬아님 2019. 9. 1. 22:14

Triangle

 

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.

Write an efficient algorithm for the following assumptions:

  • 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].

    Copyright 2009–2019 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

 

import java.util.*;

// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");

class Solution {
    public int solution(int[] A) {
        // write your code in Java SE 8
        Arrays.sort(A);
        for(int i=0 ;i<A.length-2; i++) {
            if((long)A[i] + (long)A[i+1] > A[i+2]){
                if((long)A[i+1] + (long)A[i+2] > A[i]){
                    if((long)A[i] + (long)A[i+2] > A[i+1]){
                        return 1;
                    }
                }
            }
        }
        return 0;
    }
}

 

https://app.codility.com/demo/results/trainingAFMJCS-NAY/

반응형

'개발 > 알고리즘' 카테고리의 다른 글

Codility 18번 Brackets  (0) 2019.09.02
Codility 17번 NumberOfDiscIntersections  (0) 2019.09.01
Codility 13번 MinAvgTwoSlice  (0) 2019.08.28
codility 14번 CountDiv  (0) 2019.08.26
Codlility 15번 Distinct  (0) 2019.08.26
Comments