EngTW / English-for-Programmers

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

1365. How Many Numbers Are Smaller Than the Current Number #78

Closed twy30 closed 3 years ago

twy30 commented 3 years ago

https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/

using System.Linq;

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

        // 「最大的可能的『輸入的數字』」
        const int maxPossibleInputNumber = 100;

        // 「『輸入的數字』的數量」(複數)
        var inputNumberCounts = new int[maxPossibleInputNumber + 1];

        foreach (var i in inputNumbers)
        {
            ++inputNumberCounts[i];
        }

        // 「 smaller Number 的數量」(複數)
        var smallerNumberCounts = new int[maxPossibleInputNumber + 1];

        for (int i = 1; i < smallerNumberCounts.Length; ++i)
        {
            smallerNumberCounts[i] = smallerNumberCounts[i - 1] + inputNumberCounts[i - 1];
        }

        return inputNumbers
        .Select(number => smallerNumberCounts[number])
        .ToArray();
    }
}

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

LPenny-github commented 3 years ago

@twy30 大大我又來了! 麻煩有空給予命名建議 orz。感激不盡!

using System.Linq;

public class Solution {
    public int[] SmallerNumbersThanCurrent(int[] nums) {

            // output = 升冪排列好的 input 位置索引
            // (若 input 裡有相同的數字,就取最靠近 [0] 的位置索引)

            // input =  [8,1,2,2,3]
            // 升冪排列 input = [1,2,2,3,8] 
            //         index = [0,1,2,3,4]
            // output = [4,0,1,1,3]

            int[] inputNumbers = nums;
            int[] sortedNumbers = new int[inputNumbers.Length];
            Array.Copy(inputNumbers, sortedNumbers, inputNumbers.Length);
            Array.Sort(sortedNumbers);

            return inputNumbers.Select(digit=>Array.IndexOf(sortedNumbers, digit)).ToArray();
        }
    }
twy30 commented 3 years ago

@LPenny-github 歡迎 😊


            int[] sortedNumbers = new int[inputNumbers.Length];

另一個可能性是 sortedInputNumbers


以下與命名沒有直接關係 😊

            int[] sortedNumbers = new int[inputNumbers.Length];
            Array.Copy(inputNumbers, sortedNumbers, inputNumbers.Length);

可以參考 Array.Clone() ( https://docs.microsoft.com/en-us/dotnet/api/system.array.clone?view=net-5.0 )

LPenny-github commented 3 years ago

感謝 @twy30 大大指導 orz