[HackerRank][C#] Compare the Triplets 比較三胞胎 Solution

分享

一個程式新手透過Hackrank練習程式的過程紀錄,會用自己能夠理解的白話語言來解釋,有錯誤的話請多多包涵也不吝給予指教。

問題描述

白話來說Alice和Bob創了個問題要讓審閱者評分,分為問題清晰度、獨創性、困難度(其實這些不是重點),總共要被評分三次。

Alice的分數 a = (a[0], a[1], a[2])
Bob的分數 b = (b[0], b[1], b[2]

a[0] > b[0] , Alice 得1分
a[0] = b[0] , 沒人得分
a[0] < b[0] , Bob 得1分

範圍則是1~100

簡單來說規則就是分數高的人得1分,分數相同的人則無人得分,總共比三次。

範例

input 1

5 6 7
3 6 10

output 1

1 1

intput 2

17 28 30
99 16 8

output 2

2 1

輸出入格式

HackRank 的範例 Input 為 a 和 b 兩個 int List,回傳也是一個 int List。

public static List<int> compareTriplets(List<int> a, List<int> b)

Solution 1

想法很簡單,既然要比三次,那就每一個取出來比就好啦 XD,這個做法算是熟悉一下 List 的用法跟 三元運算子 ?: 的技巧。

    /*
     * Complete the 'compareTriplets' function below.
     *
     * The function is expected to return an INTEGER_ARRAY.
     * The function accepts following parameters:
     *  1. INTEGER_ARRAY a
     *  2. INTEGER_ARRAY b
     */

    public static List<int> compareTriplets(List<int> a, List<int> b)
    {
        int pointa = (a[0]>b[0]?1:0) + (a[1]>b[1]?1:0) + (a[2]>b[2]?1:0);
        int pointb = (a[0]<b[0]?1:0) + (a[1]<b[1]?1:0) + (a[2]<b[2]?1:0);
        
        List<int> result = new List<int>();
        result.Add(pointa);
        result.Add(pointb);
        
        return result;

    }

Solution 2

換個 for 迴圈的方式來解,讓整體看起來比較有簡潔跟彈性,譬如今天這兩個人要比50題…XD

特別要注意的是 List 長度要用 Count 計算。

    /*
     * Complete the 'compareTriplets' function below.
     *
     * The function is expected to return an INTEGER_ARRAY.
     * The function accepts following parameters:
     *  1. INTEGER_ARRAY a
     *  2. INTEGER_ARRAY b
     */

    public static List<int> compareTriplets(List<int> a, List<int> b)
    {
        List<int> scores = new List<int>() {0 , 0};
        
        for (int i=0;i<a.Count();i++) {
            if(a[i]>b[i]) scores[0]++;
            if(a[i]<b[i]) scores[1]++;
        }
        
        return scores;

    }
分享
Scroll to Top