Find the Median

Sort by

recency

|

557 Discussions

|

  • + 0 comments
    def findMedian(arr):
        arr.sort()
        return arr[len(arr)//2]
    
  • + 0 comments

    Java solution.

    public static int findMedian(List<Integer> arr) {
            PriorityQueue<Integer> minHeap = new PriorityQueue<>(Comparator.naturalOrder());
            
            PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
            
            for (int n : arr) {
                minHeap.offer(n);
                maxHeap.offer(minHeap.poll());
                
                if (maxHeap.size() > minHeap.size()) {
                    minHeap.offer(maxHeap.poll());
                }
            }
            if (minHeap.size() > maxHeap.size()) {
                return minHeap.peek();
            } else {
                long median = (minHeap.peek() + maxHeap.peek()) / 2;
                return (int) median;
            }
        }
    
  • + 0 comments

    Here is my c++ solution, you can watch the explanation here https://youtu.be/CbEYUUopR-8

    int findMedian(vector<int> arr) {
        sort(arr.begin(), arr.end());
        return arr[arr.size() / 2];
    }
    
  • + 0 comments

    C#:

    public static int findMedian(List<int> arr)
        {
           arr.Sort();
           int middleIndex = arr.Count/2;
           return  arr[middleIndex];
        }
    
  • + 0 comments

    Here is my one line Python solution! I'm suprised with how this challenge is worth 35 points when you can solve it in one line!

    def findMedian(arr):
        return sorted(arr)[len(arr) // 2]