Codility – Lesson 3 Time Complexity – TapeEquilibrium
プログラミング能力を評価するオンラインテスト、Codilityで、Lesson 3 Time Complexity – TapeEquilibriumに回答しました。
問題と結果画面
66%の評価。
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 35 36 37 38 39 40 41 |
using System; using System.Collections.Generic; class Solution { public int solution(int[] A) { List<int> difList = new List<int>(); for(int i = 1; i < A.Length; i++) { int totalFormer = 0; int totalAfter = 0; int dif = 0; for(int j = 0; j < i; j++) { totalFormer += A[j]; } for(int j = i; j < A.Length; j++) { totalAfter += A[j]; } dif = System.Math.Abs (totalFormer - totalAfter); difList.Add(dif); } int min = difList[0]; for(int i = 1; i < difList.Count; i ++) { if(difList[i] < min) { min = difList[i]; } } return min; } } |
66%の評価。
問題と結果画面
for文の数を4つから3つに。
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 |
using System; using System.Collections.Generic; class Solution { public int solution(int[] A) { int min = -1; for(int i = 1; i < A.Length; i++) { int totalFormer = 0; int totalAfter = 0; int dif = 0; for(int j = 0; j < i; j++) { totalFormer += A[j]; } for(int j = i; j < A.Length; j++) { totalAfter += A[j]; } dif = System.Math.Abs (totalFormer - totalAfter); if(min < 0 || dif < min) min = dif; } return min; } } |
問題と結果画面
66%の評価。
for文の数を3つから2つに。
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 |
using System; class Solution { public int solution(int[] A) { int sum = 0; foreach (int a in A) { sum += a; } int min = -1; for(int i = 1; i < A.Length; i++) { int sumFormer = 0; int sumAfter = 0; int dif = 0; for(int j = 0; j < i; j++) { sumFormer += A[j]; } sumAfter = (sum - sumFormer); dif = System.Math.Abs (sumFormer - sumAfter); if(min < 0 || dif < min) min = dif; } return min; } } |
問題と結果画面
100%の評価。
for文の数を2つから1つに。
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 |
using System; class Solution { public int solution(int[] A) { int sum = 0; foreach (int a in A) { sum += a; } int min = -1; int sumFormer = 0; for(int i = 0; i < A.Length - 1; i++) { sumFormer += A[i]; int dif = System.Math.Abs (sumFormer - (sum - sumFormer)); if(min < 0 || dif < min) min = dif; } return min; } } |