An accepted java solution and a minor question


  • 0

    The following solution is accepted. I know it is not the best.

    public class Solution {

    public int majorityElement(int[] num) {
        int n = num.length;
        HashMap<Integer, Integer> hsMap = new HashMap<Integer, Integer>();
        for(int i = 0; i < n; i++)
        {
            if(hsMap.get(num[i]) == null)
            {
                hsMap.put(num[i], 1);
                if( 1 > n/2)
                    return num[i];
            }
            else // hsMap.get(num[i]) != null
            {
                if (hsMap.get(num[i]) + 1 > n/2 )
                    return num[i];
                    
                hsMap.put(num[i], hsMap.get(num[i]) + 1);
            }
        }        
        return -1;
    }
    

    }

    My question is that, the last statement " return -1;" will never be executed, if it is guaranteed to have a majority element. However, if I delete this statement, it will cause " missing return statement " error. Why must I need the last return statement, if it is guaranteed to have a majority element ?


  • 0
    M

    Hi there. Per the java spec, since you defined your function to return an int, the function must always return an int. The 2 other return statements above are behind conditionals that could prevent their execution. So, without the last return statement, it is possible that the function wouldn't return an int, and so the compiler detects this and throws the "missing return statement" error.


Log in to reply
 

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