Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

1640. Check Array Formation Through Concatenation #85

Closed
twy30 opened this issue Nov 4, 2020 · 2 comments · Fixed by #90
Closed

1640. Check Array Formation Through Concatenation #85

twy30 opened this issue Nov 4, 2020 · 2 comments · Fixed by #90
Labels

Comments

@twy30
Copy link
Contributor

twy30 commented Nov 4, 2020

https://leetcode.com/problems/check-array-formation-through-concatenation/

using System.Collections.Generic;

public class Solution
{
    public bool CanFormArray(int[] arr, int[][] pieces)
    {
        // 「輸入的數字」(複數)
        var inputNumbers = arr;

        // 「『輸入的數字』的索引值」
        var inputNumberIndexes = new Dictionary<int, int>();

        for (int i = 0; i < inputNumbers.Length; i++)
        {
            inputNumberIndexes.Add(inputNumbers[i], i);
        }

        foreach (var piece in pieces)
        {
            // 「 piece 起始索引值」
            int pieceStartIndex;
            if (inputNumberIndexes.TryGetValue(piece[0], out pieceStartIndex))
            {
                for (int i = 0; i < piece.Length; ++i)
                {
                    // 「『比對』索引值」
                    var comparisonIndex = pieceStartIndex + i;

                    if (comparisonIndex >= inputNumbers.Length) { return false; }

                    if (piece[i] != inputNumbers[comparisonIndex]) { return false; }
                }
            }
            else
            {
                return false;
            }
        }

        return true;
    }
}

請參考「刷 LeetCode 練習命名」 #69 😊

@twy30
Copy link
Contributor Author

twy30 commented Nov 4, 2020

這裡遇到個很有趣的情形

            // 「 piece 在 InputNumbers 中的起始索引值」, "piece" 取自 LeetCode 題目敘述用字
            var pieceStartIndexInInputNumbers = inputNumberIndexes[piece[0]];

pieceStartIndexInInputNumbers 由 6 個英文字組成,雖然在英文語法、語意上算是清楚,但不易閱讀。

或許這裡應該採用折衷的做法 🤔 例如:

  • 變數名稱縮為 pieceStartIndex
  • 另外寫註解補充其使用情景脈絡

@twy30 twy30 added the LeetCode label Nov 4, 2020
@twy30
Copy link
Contributor Author

twy30 commented Nov 6, 2020

更新 LeetCode 解答,採用「變數名稱縮為 pieceStartIndex」。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

Successfully merging a pull request may close this issue.

1 participant