Accepted Java solution, why don't just sort and return the first element ?


  • -7
    L
    public class Solution {
    public int findMin(int[] num) {
        if(num == null) return 0;
        
        Arrays.sort(num);
        
        return num[0];
    }
    

    }


  • 0
    M

    Your answer works but the run time is O(n logn), while there is a log(n) solution for this. That might come up in an interview.


  • 0
    L

    Thank you for explanation, I did not notice that.


  • 0
    M

    Your solution has a time complexity of O(n log(n)), and that is not good.

    A naive solution can be done in O(n), checking all the elements checking for the minimum, and the best solution can be done using a modified binary search (check the editorial of this problem).


  • 0
    S

    I am not familiar with Java. (So, if I am wrong, never mind.)
    But I have a question about your solution.
    Consider the following test case:
    [1,2,2,2,3] or [3,2,2,2,1]
    Although you sorted the array, but the majority element is not the first one. Am I right?


  • 0
    F

    it's because if you sort, you fail the interview.


Log in to reply
 

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