Codility – Lesson 4 Time Complexity – FrogRiverOne
プログラミング能力を評価するオンラインテスト、Codilityで、Lesson 4 Time Complexity – FrogRiverOneに回答しました。
問題と結果画面
63%の評価。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
using System; using System.Collections.Generic; class Solution { public int solution(int X, int[] A) { List<bool> checkList = new List<bool>(); for(int i = 0; i < X; i++) { checkList.Add(false); } for(int i = 0; i < A.Length; i++) { if(A[i] <= X) { checkList[(A[i] - 1)] = true; } bool allTrue = true; for(int j = 0; j < checkList.Count; j++) { if(checkList[j] == false) allTrue = false; } if(allTrue) return i; } // couldn't get to the other side of the river. return -1; } } |
問題と結果画面
72%の評価。
for文の数を3つから1つに。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.Linq; class Solution { public int solution(int X, int[] A) { bool[] checkList = new bool[X]; for(int i = 0; i < A.Length; i++) { if(A[i] <= X) { checkList[(A[i] - 1)] = true; } if(checkList.All (x => x == true)) return i; } // couldn't get to the other side of the river. return -1; } } |
問題と結果画面
81%の評価。
LINQより、ArrayのTrueForAllメソッドの方が若干パフォーマンスは良いみたいだ。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; class Solution { public int solution(int X, int[] A) { bool[] checkList = new bool[X]; for(int i = 0; i < A.Length; i++) { if(A[i] <= X) { checkList[(A[i] - 1)] = true; } if(System.Array.TrueForAll (checkList, x => x == true)) return i; } // couldn't get to the other side of the river. return -1; } } |
問題と結果画面
100%の評価。
シンプルにカウンタをデクリメントすることで100%を達成。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; class Solution { public int solution(int X, int[] A) { bool[] checkList = new bool[X]; int cnt = X; for(int i = 0; i < A.Length; i++) { if(!checkList[(A[i] - 1)] && A[i] <= X) { checkList[(A[i] - 1)] = true; cnt--; } if(cnt == 0) return i; } // couldn't get to the other side of the river. return -1; } } |