문제: app.codility.com/programmers/lessons/8-leader/dominator/
Dominator coding task - Learn to Code - Codility
Find an index of an array such that its value occurs at more than half of indices in the array.
app.codility.com
결과: 91% 다시 풀어야 함.
if (A.Length == 0)
return -1;
else if (A.Length == 1)
return 0;
Dictionary<int, int> dic = new Dictionary<int, int>();
for (int i = 0; i < A.Length; i++)
{
if (dic.ContainsKey(A[i]))
{
int cnt = 0;
dic.TryGetValue(A[i], out cnt);
dic[A[i]] = cnt + 1;
}
else
{
dic.Add(A[i], 1);
}
}
List<int> listKey = new List<int>(dic.Keys);
List<int> listVal = new List<int>(dic.Values);
listVal.Sort();
int max = listVal[listVal.Count - 1];
int leader = -1;
if (max == listVal[listVal.Count - 2])
return -1;
else if (max > A.Length / 2)
{
for (int i = 0; i < listKey.Count; i++)
{
int key = listKey[i];
int val = 0;
dic.TryGetValue(key, out val);
if (val == max)
{
leader = key;
break;
}
}
for (int i = 0; i < A.Length; i++)
{
if (A[i] == leader)
return i;
}
}
return leader;
'공부하자 > Codility' 카테고리의 다른 글
[Codility] Lesson9. MaxDoubleSliceSum (C#) (0) | 2020.11.20 |
---|---|
[Codility] Lesson8. EquiLeader (C#) (0) | 2020.11.20 |
[Codility] Lesson7. StoneWall (C#) (0) | 2020.11.20 |
[Codility] Lesson7. Nesting (C#) (0) | 2020.11.20 |
[Codility] Lesson7. Fish (C#) (0) | 2020.11.20 |