EngTW / English-for-Programmers

《程式英文》:用英文提昇程式可讀性
977 stars 45 forks source link

1512. Number of Good Pairs #74

Closed twy30 closed 3 years ago

twy30 commented 3 years ago

https://leetcode.com/problems/number-of-good-pairs/

using System.Collections.Generic;
using System.Linq;

public class Solution
{
    public int NumIdenticalPairs(int[] nums)
    {
        // 「輸入的數字」(複數)
        var inputNumbers = nums;

        // 「『輸入的數字』的數量」(複數)
        var inputNumberCounts = new Dictionary<int, int>();

        foreach (var i in inputNumbers)
        {
            if (inputNumberCounts.ContainsKey(i))
            {
                ++inputNumberCounts[i];
            }
            else
            {
                inputNumberCounts[i] = 1;
            }
        }

        return inputNumberCounts.Sum(count => count.Value * (count.Value - 1) / 2);
    }
}

請參考「刷 LeetCode 練習命名」 https://github.com/EngTW/English-for-Programmers/issues/69 😊

LPenny-github commented 3 years ago

又來麻煩大大,尋求命名建議了 orz 感激不盡 orz

public int IdenticalPairsCount(int[] inputNumbers)
        {
            int numberOfIdenticalPairs = 0;

            for (int index = 0; index < inputNumbers.Length-1; ++index)
            {
                for (int nextIndex = index+1; nextIndex< inputNumbers.Length; ++nextIndex)
                {
                    if (inputNumbers[index] == inputNumbers[nextIndex] )
                    {
                        ++numberOfIdenticalPairs;
                    }
                }
            }

            return numberOfIdenticalPairs;
        }
twy30 commented 3 years ago

@LPenny-github

堅持「刻意練習」,一定會進步的 💪


            int numberOfIdenticalPairs = 0;

這個命名很好懂 👍

另外可能的寫法有 identicalPairCount, quantityOfIdenticalPairs 等組合。


            for (int index = 0; index < inputNumbers.Length-1; ++index)
            {
                for (int nextIndex = index+1; nextIndex< inputNumbers.Length; ++nextIndex)

這個地方,或許可以用 i, j 來代替 index, nextIndex 🤔

我的想法是:

不過,當作練習,如果我們就是不想要用 i, j, 那麼,要怎麼命名這兩個索引值變數?

我想我會沿用 LeetCode 題目中的用詞 "good pair", 然後寫成

🤔

LPenny-github commented 3 years ago

@twy30 感謝大大的鼓勵和指教 orz