정수배열 a에서 0번째와 같은 값들을 배열 a의 수가 0 남을 때 까지 혹은 지운 수가 1일때까지 반복.
- (지운 수가 1개라면 단일이기 때문에 값을 반환)
* 배열 a가 한개라면 이미 단일이기 때문에 바로 반환.
using System; using System.Collections.Generic; using System.IO; using System.Linq; class Solution {
static int lonelyinteger(int[] a) { // Complete this function if(a.Length > 1) { List<int> A = new List<int>(a); while(A.Count > 0) { int tmp = A[0]; int tmp2 = A.RemoveAll(obj => obj == tmp); if(tmp2 == 1) { return tmp; } } } return a[0]; }
static void Main(String[] args) { int n = Convert.ToInt32(Console.ReadLine()); string[] a_temp = Console.ReadLine().Split(' '); int[] a = Array.ConvertAll(a_temp,Int32.Parse); int result = lonelyinteger(a); Console.WriteLine(result); } }
해결방법2.
* 단일 정수나 중복이 없는 수를 찾을 때는 XOR을 사용하면 빠르다.
배열 a를 XOR(^)로 연산.
using System; using System.Collections.Generic; using System.IO; using System.Linq; class Solution {
static int lonelyinteger(int[] a) { // Complete this function int _output = a[0]; if(a.Length > 1) { for(int i = 1; i < a.Length; i++) { _output ^= a[i]; } } return _output; }
static void Main(String[] args) { int n = Convert.ToInt32(Console.ReadLine()); string[] a_temp = Console.ReadLine().Split(' '); int[] a = Array.ConvertAll(a_temp,Int32.Parse); int result = lonelyinteger(a); Console.WriteLine(result); } }
17.12.07(0005)
회고 : 잊고 살던 XOR을 다시 공부했다.
XOR(두 수가 다를때 1)
단일정수를 구하거나 둘 중 하나만 참일때 같은 문제(홀수일때 참. 과거 님게임) 짝이 맞지 않는(오류코드)수를 찾을 때 유용..