zoukankan      html  css  js  c++  java
  • [LintCode笔记了解一下]80.Median

    Given a unsorted array with integers, find the median of it.

    A median is the middle number of the array after it is sorted.

    If there are even numbers in the array, return the N/2-th number after sorted.

    思路:

    找个sort方法sort完后即可

    最简单的就是bubble sort

    但是bubble sort时间复杂度太大,所以改用quicksort

    /* This function takes last element as pivot, places
       the pivot element at its correct position in sorted
        array, and places all smaller (smaller than pivot)
       to left of pivot and all greater elements to right
       of pivot */
    int partition (int arr[], int low, int high)
    {
        int pivot = arr[high];    // pivot
        int i = (low - 1);  // Index of smaller element
     
        for (int j = low; j <= high- 1; j++)
        {
            // If current element is smaller than or
            // equal to pivot
            if (arr[j] <= pivot)
            {
                i++;    // increment index of smaller element
                swap(&arr[i], &arr[j]);
            }
        }
        swap(&arr[i + 1], &arr[high]);
        return (i + 1);
    }
     
    /* The main function that implements QuickSort
     arr[] --> Array to be sorted,
      low  --> Starting index,
      high  --> Ending index */
    void quickSort(int arr[], int low, int high)
    {
        if (low < high)
        {
            /* pi is partitioning index, arr[p] is now
               at right place */
            int pi = partition(arr, low, high);
     
            // Separately sort elements before
            // partition and after partition
            quickSort(arr, low, pi - 1);
            quickSort(arr, pi + 1, high);
        }
    }
  • 相关阅读:
    HBase 安装设置
    Python中通过函数对象创建全局变量
    Scala 中 构造函数,重载函数的执行顺序
    Hive 安装配置
    976. 三角形的最大周长
    922. 按奇偶排序数组 II
    350. 两个数组的交集 II
    349. 两个数组的交集
    242. 有效的字母异位词
    925. 长按键入
  • 原文地址:https://www.cnblogs.com/otakuhan/p/8607281.html
Copyright © 2011-2022 走看看