Codility – Lesson 2 Arrays – OddOccurrencesInArray
プログラミング能力を評価するオンラインテスト、Codilityで、Lesson 2 Arrays – OddOccurrencesInArrayに回答しました。
問題と結果画面
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 |
using System; class Solution { public int solution(int[] A) { bool isUnpaired; for (int i = 0; i < A.Length; i++) { if(A [i] == 0) continue; isUnpaired = true; for(int j = i + 1; j < A.Length; j++) { if(A [i] == A [j]) { isUnpaired = false; A [j] = 0; break; } } if (isUnpaired) { return A [i]; } } return 0; } } |
問題と結果画面
100%の評価。
for文を2つから1つに。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using System; class Solution { public int solution(int[] A) { System.Array.Sort(A); for (int i = 0; i < A.Length; i++) { if(A [i] < 1 || 1000000000 < A [i]) throw new System.InvalidOperationException(); if((i % 2) == 1) continue; if(A.Length <= i + 1) return A [i]; if(A [i] != A [i + 1]) return A [i]; } return 0; } } |
問題と結果画面
100%の評価。
XOR演算子を使えばこんなに簡潔にも書ける。
ビット演算っておもしろい。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; class Solution { public int solution(int[] A) { int unpairedInt = 0; foreach (int val in A) { unpairedInt ^= val; } return unpairedInt; } } |