zoukankan      html  css  js  c++  java
  • LintCode "Median"

    Partial Sort.

    class Solution {
    public:
        /**
         * @param nums: A list of integers.
         * @return: An integer denotes the middle number of the array.
         */
        int partition(vector<int> &nums, int s, int e)
        {
            if (s > e) return -1;
    
            int pivot = nums[s];
            swap(nums[s], nums[e]);
            int i = s, j = s;
            while(j < e)
            {
                if(nums[j] <= pivot)
                {
                    swap(nums[i ++], nums[j]);
                }
                j ++;
            }
            swap(nums[i], nums[e]);
    
            return i;   
        }
        int findKth(vector<int> &nums, int inx, int s, int e)
        {
            int pi = partition(nums, s, e);
            if(pi == inx) return nums[inx];
            if (pi < inx) return findKth(nums, inx, pi+1, e);
            return findKth(nums, inx, s, pi-1);
        }
        int median(vector<int> &nums) {
            size_t len = nums.size();
            int mid = len/2 - (len%2?0:1);
            return findKth(nums, mid, 0, len - 1);
        }
    };
    View Code
  • 相关阅读:
    最短路(Floyed、Dijkstra、Bellman-Ford、SPFA)
    查找技术
    简单线段树
    dfs
    bfs
    插件工具集合
    Web前端代码规范
    Javascript 判断手机横竖屏状态
    Git 笔记2
    git 笔记 1
  • 原文地址:https://www.cnblogs.com/tonix/p/4809044.html
Copyright © 2011-2022 走看看