LeetCode---排序

只能做防骑 2020-06-08

目录



#853 车队

https://leetcode-cn.com/problems/car-fleet/

这题我并没有使用某个排序算法,只是使用了Vector的可自定义sort方法。

class Solution {
public:
   struct Car
    {
        int pos;
        int speed;
        float time;
        Car(int p,int s,float t)
        {
            pos = p;
            speed = s;
            time = t;
        }
    };

    static bool compare(const Car& c1,const Car& c2)
    {
        if(c1.pos != c2.pos){
            return c1.pos <= c2.pos;
        }
        return c1.speed <= c2.speed;
    }

    int carFleet(int target, vector<int>& position, vector<int>& speed)
    {
        int length = position.size();
        if(length==0)
            return 0;
        else if(length == 1)
            return 1;

        vector<Car> cars;

        for(int i=0;i<length;i++){
            Car temp(position[i],speed[i],(target-position[i])/(float)speed[i]);
            cars.push_back(temp);
        }

        sort(cars.begin(),cars.end(),compare);

        int count = 0;

        for(int i=length-1;i>=0;i--){
            if(i < length - 1 && cars[i].time <= cars[i + 1].time){
                cars[i].time = cars[i + 1].time;
            }else{
                count++;
            }
        }
        
        return count;
    }
};

#17.14 最小k个数

https://leetcode-cn.com/problems/smallest-k-lcci/

堆排序,这里使用最小堆

class Solution {
public:
    vector<int> smallestK(vector<int>& arr, int k)
    {
        vector<int> result;

        if(k>=arr.size())
            return arr;

        //构建小顶堆,非叶子节点个数
        for (int i = arr.size() / 2 - 1; i >= 0; i--)
        {
            //从第一个非叶子结点从下至上,从右至左调整结构
            AdjustHeap(arr, i, arr.size(),result);
        }
        //每次把堆顶元素与末尾元素进行交换,获取一个最小的,然后继续调整堆
        for (int j = arr.size()-1; j >= arr.size()-k; j--)
        {
            SwapNum(arr, 0, j);
            result.push_back(arr[j]);
            AdjustHeap(arr, 0, j,result);
        }

        return result;
    }

    void AdjustHeap(vector<int>& arr, int i, int length,vector<int>& result)
    {
        int temp = arr[i];//先取出当前元素i
        for (int k = i * 2 + 1; k < length; k = k * 2 + 1)
        {
            //如果节点i的下面两个子节点中最小的比其小,则交换

            //让k指向2个中最大的子节点
            if (k + 1 < length && arr[k] > arr[k + 1])
                k++;

            //交换
            if (arr[k] < temp)
            {
                arr[i] = arr[k];
                i = k;
            }
            else
            {
                break;
            }
        }
        arr[i] = temp;
    }


    void SwapNum(vector<int>& arr, int a, int b)
    {
        int temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }
};

相关推荐