I have a function in java which may have bug and I can not find it : <p>I have this code which suppose to do the following task:
For example , given M=3, and array built like this:</p>

<pre><code>A[0]=1
A[1]=1
A[2]=3
A[3]=3
A[4]=5
A[5]=1
A[6]=3
</code></pre>

<p>the function may return 1 or 3</p>

<pre><code>import java.util.*;

class Solution {
    int solution(int M, int[] A) {
        int N = A.length;
        int[] count = new int[M + 1];
        for (int i = 0; i &lt;= M; i++)
            count[i] = 0;
        int maxOccurence = 1;
            int index = -1;
            for (int i = 0; i &lt; N; i++) {
                if (count[A[i]] &gt; 0) {
                    int tmp = count[A[i]];
                    if (tmp &gt; maxOccurence) {
                        maxOccurence = tmp;
                        index = i;
                    }
                    count[A[i]] = tmp + 1;
                } else {
                    count[A[i]] = 1;
                }
            }
            return A[index];
        }
    }
</code></pre>

<p>what could be the problem because it is not always working and I can see there is a bug in my program.</p>
