본문 바로가기

공부하자/Codility

[Codility] Lesson8. EquiLeader (C#)

 

문제: app.codility.com/programmers/lessons/8-leader/equi_leader/

 

EquiLeader coding task - Learn to Code - Codility

Find the index S such that the leaders of the sequences A[0], A[1], ..., A[S] and A[S + 1], A[S + 2], ..., A[N - 1] are the same.

app.codility.com

 

 

결과: 88% 다시 풀어야 함.. 하아.. 언제 풀려나..ㅠ

 

            Dictionary<int, int> dic = new Dictionary<int, int>();
            int max = 0;
            int index = 0;
            int result = 0;
            int count = 0;

            for (int i = 0; i < A.Length; i++)
            {
                if (dic.ContainsKey(A[i]))
                {
                    dic[A[i]] += 1;
                    if (max < dic[A[i]])
                    {
                        max = dic[A[i]];
                        index = A[i];
                    }
                }
                else
                {
                    dic.Add(A[i], 1);
                }
            }

            if (max < A.Length / 2)
                return 0;

            for (int i = 0; i < A.Length; i++)
            {
                if (A[i] == index)
                {
                    count++;
                    dic[index]--;
                }

                if (dic[index] > (A.Length - (i + 1)) / 2 && count > (i + 1) / 2)
                    result++;
            }

            return result;