接續前一篇文章,線上程式設計考試Codility測試題,答案還能再優化,之前想的太複雜了

以下直接暴雷答案,想自行挑戰的讀者請勿往下看

codility.jpg

還好Codility沒記憶體使用量測試,上次的答案太浪費記憶體,這次答案減少75%記憶體使用量(int[] -> bool[]),運行速度也更快

 

 

 

 

 

 

 

 

 

 

 

class Solution {
    public int solution(int[] A) {
        
        const int arrMax = 1000001;

        bool[] _a = new bool[arrMax]; //空間換時間

        foreach (int item in A)
        {
            if (item <= 0)
            {
                continue;
            }

            _a[item] = true;
        }

        for (int i = 1; i < arrMax; ++i)
        {
            if (!_a[i])
            {
                return i;
            }
        }

        return 1;
    }
}

創作者介紹
創作者 GNAySolution 的頭像
Yang

GNAySolution

Yang 發表在 痞客邦 留言(0) 人氣( 37 )