Find the Median

Sort by

recency

|

559 Discussions

|

  • + 0 comments
    def findMedian(arr):
        # Write your code here
        low = 0
        high = len(arr) - 1
        mid = (low + high) // 2
        
        return sorted(arr)[mid]
    
  • + 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

    My Java solution:

    public static int findMedian(List<Integer> arr) {
            //goal: find median from a sorted array
            //sort the arr
            Collections.sort(arr);
            
            //return char at middle idx
            int middleIdx = arr.size() / 2;
            return arr.get(middleIdx);
        }
    
  • + 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;
            }
        }