Find the Median

Sort by

recency

|

546 Discussions

|

  • + 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 solution in golang:

    func findMedian(arr []int32) int32 {
        var median []int32
    
        sort.Slice(arr, func(i, j int) bool {
            return arr[i] < arr[j]
        })
    
        if len(arr)%2 == 0 {
            median = append(median, arr[len(arr)/2-1])
    
        } else {
            median = append(median, arr[len(arr)/2])
    
        }
        return median[0]
    
    }
    
  • + 0 comments

    simple python solve

    **

    def findMedian(arr):

        arr.sort()
    
        return arr[len(arr)//2]
        **
    
  • + 0 comments
        public static int findMedian(List<int> arr)
        {
            var middleElementIndex = Math.Ceiling(arr.Count / 2.0) - 1;
            
            arr.Sort();
            
            return arr[(int)middleElementIndex];
        }
    
  • + 2 comments

    Can anyone explain why this doesn't work?

    function findMedian(arr: number[]): number {
    	let sorted = arr.sort();
    	const mid = Math.floor(arr.length / 2);
    	return sorted[mid];
    	}