My accepted Java solution


  • 0
    A

    An example for explanation:

    num[]={1,0,1,0,0,1}

    res[]={1,1,2,2,3,1}

    res[i] means num[i]'s appears times, and if res[i] > num.length/2 , return num[i].

    public class Solution {
        public int majorityElement(int[] num) {
            int[] res=new int[num.length];
            res[0]=1;
            for(int i=1;i<num.length;i++)
            {
                for(int j=i-1;j>=0;j--)
                {
                    if(num[i]==num[j])
                    {
                        res[i]=res[j]+1;
                        break;
                    }
                }
                if(res[i]==0) res[i]=1;
                else if(res[i]>(num.length/2))
                {
                    return num[i];
                }
            }
            return num[0];
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.