Time limit exceeded and correct answer for the same code in java O(M+N) space complexity


#1

I got time limit exceeded upon submission, but when I submitted again and again the same code I sometimes got correct answer

public class Solution {
public void setZeroes(ArrayList<ArrayList> a) {
int R = a.size();
int C = a.get(0).size();
int rows[] = new int[R];
int cols[] = new int[C];
int i,j;
for(i=0; i<R; i++)
for(j=0; j<C; j++)
{
if(a.get(i).get(j)==0)
{
rows[i]++;
cols[j]++;
}
}
for(i=0; i<R; i++)
{
if(rows[i]>0)
{
for(j=0; j<C; j++)
{
a.get(i).set(j,0);
}
}
}
for(i=0; i<C; i++)
{
if(cols[i]>0)
{
for(j=0; j<R; j++)
{
a.get(j).set(i,0);
}
}
}
}
}strong text