九日集训第五天(排序api)

本文分享了C++面试中常见的五个问题,包括快速排序实现、多数元素查找、重复元素检测、最大间距和奇偶排序数组。通过实例演示和代码,复习排序算法及数据结构在实际问题中的应用。

前言

记录几个面试常见题型

一、知识点

C语言中sort api 的使用 ,compare
一道排序题目,数据范围是关键,如果这道题目只能让我们使用O(nlogn)O(nlogn)的算法,显然我们可以选择快速排序,归并排序等算法,这里我们就使用快速排序.

时间复杂度图
在这里插入图片描述

二、题目

1、排序数组

1.1 分析
可以直接用 stl sort
这里封装了一个快排函数,顺便复习下排序算法

1.2代码

class Solution {
public:
   vector<int> sortArray(vector<int>& nums) {
       srand((unsigned)time(NULL));
       quick_sort(nums,0 , (int) nums.size() - 1);

       return nums;
       

    }
    void quick_sort(vector<int>& q, int l, int r)
{
    if (l >= r) return;

    int i = l - 1, j = r + 1, x = q[l + r >> 1];
    while (i < j)
    {
        do i ++ ; while (q[i] < x);
        do j -- ; while (q[j] > x);
        if (i < j) swap(q[i], q[j]);
    }

    quick_sort(q, l, j);
    quick_sort(q, j + 1, r);
}


};

2、多数元素
2.1题目分析
简单题,读懂题目就行
2.2代码


class Solution {
public:
    int majorityElement(vector<int>& nums) {

        sort(nums.begin(),nums.end());

        return nums[nums.size()/2];

    }
};

3存在重复元素
3.1题目分析
专栏给的遍历法,自己使用了 map 方便
3.2代码

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {

        unordered_map<int,int> m;

        for(int i = 0 ; i < nums.size(); i ++)
            if(m.count(nums[i]))
                return true;

            else m[nums[i]] ++;

        return false;
    }
};

4最大间距
4.1题目分析
恢复有序,在遍历找答案
4.2代码

class Solution {
public:
    int maximumGap(vector<int>& nums) {

        int n = nums.size() , max  = 0 , tem = 0;

        if(n < 2) return 0;
        sort(nums.begin() , nums.end());
        for(int i = 1 ; i < n ; i ++)
        {   
            tem = nums[i] - nums[i - 1];
            if(tem> max)
                max = tem;
        }

        return max;

    }
};

5按奇偶排序数组
5.1题目分析
用双端列表 ,前后添加
5.2代码

class Solution {
public:
    vector<int> sortArrayByParity(vector<int>& nums) {

        deque<int> ans;

        int n = nums.size();

        for(int i = 0 ;  i < n ; i ++)
        {
            if(nums[i]%2)
                ans.push_back(nums[i]);
            else
                ans.push_front(nums[i]);
        }

        return vector<int>(d.begin(),d.end());

    }
    
};

三、做题记录

在这里插入图片描述







评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值