1.12-1.18

一、算法题

1.  215. 数组中的第K个最大元素

给定整数数组 nums 和整数 k,请返回数组中第 k 个最大的元素。

请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。

你必须设计并实现时间复杂度为 O(n) 的算法解决此问题。


示例 1:

输入: [3,2,1,5,6,4], k = 2
输出: 5
示例 2:

输入: [3,2,3,1,2,4,5,5,6], k = 4
输出: 4
class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        a = sorted(nums)
        return a[len(a)-k]

2.  92. 反转链表 II

给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。

示例 1:
输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]
示例 2:
输入:head = [5], left = 1, right = 1
输出:[5]
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* reverseBetween(struct ListNode* head, int left, int right) {
    struct ListNode *dummyNode = malloc(sizeof(struct ListNode));
    dummyNode->val = -1;
    dummyNode->next = head;

    struct ListNode *pre = dummyNode;
    for (int i = 0; i < left - 1; i++) {
        pre = pre->next;
    }
    struct ListNode *cur = pre->next;
    struct ListNode *next;
    for (int i = 0; i < right - left; i++) {
        next = cur->next;
        cur->next = next->next;
        next->next = pre->next;
        pre->next = next;
    }
    return dummyNode->next;
}

3.  236. 二叉树的最近公共祖先

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

示例 1:
输入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出:3
解释:节点 5 和节点 1 的最近公共祖先是节点 3 。
示例 2:
输入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
输出:5
解释:节点 5 和节点 4 的最近公共祖先是节点 5 。因为根据定义最近公共祖先节点可以为节点本身。
示例 3:
输入:root = [1,2], p = 1, q = 2
输出:1
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* dfs(struct TreeNode* root,struct TreeNode* p, struct TreeNode* q)  //深度优先搜索
{
    if(root==NULL||root==p||root==q) //返回当前节点的值
    {
        return root;
    }
    struct TreeNode* left = dfs(root->left,p,q);
    struct TreeNode* right = dfs(root->right,p,q);
    if(left==NULL&&right==NULL)
    {
        return NULL;
    }
    else if(left==NULL)
    {
        return right;
    }
    else if(right==NULL)
    {
        return left;
    }
    else{
        return root;
    }
}

struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
    return dfs(root,p,q);
}

4.  102. 二叉树的层序遍历

给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。

示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]
示例 2:
输入:root = [1]
输出:[[1]]
示例 3:
输入:root = []
输出:[]
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
 #define max_num 2000
int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes) {
    if (root == NULL) {
    *returnSize = 0;
    return NULL;
}
*returnSize = 0;
int front =0;
int rear =0;
int **ans =(int *)malloc(sizeof(int *)*max_num);
int returnCnt =0;
struct TreeNode*q[max_num]={0};
q[rear++]=root;
int *column =(int *)malloc(sizeof(int)*max_num);
while (front<rear) {
    int curSize=rear-front;
    ans[returnCnt] = (int*)malloc(sizeof(int)*curSize);
    column[returnCnt]=curSize;
    for(int i=0;i<curSize;i++)
    {        
        ans[returnCnt][i]=q[front]->val;
        if(q[front]->left!=NULL){
            q[rear++]=q[front]->left;
        }
         
        if(q[front]->right!=NULL){
            q[rear++]=q[front]->right;
        }
        front++;
    }
    returnCnt++;
}
*returnSize =returnCnt;
* returnColumnSizes = column;
return ans;
}

二、本周学习

本周首先复习了放假前学习过的知识

1.Numpy

python内置包,主要是数组上的数学操作

使用前首先要导入numpy库,此处导入后命名为np

import numpy as np

产生数组a

l = [1,2,3,4]
a = np.array(l)      #从列表产生数组
a = np.array([1,2,3,4])    #从列表传入
a = np.zeros(5)          #生成全0数组
a = np.ones(5)       #生成全1数组
a = np.arange(1,10)   #生成整数序列
a = np/linspace(1,10,10)    #生成等差数列(起点,终点,数组个数)
a = np.random.rand(10)     #生成0-1范围内随机数10个
a = np.random.randn(10)    #生成服从标准正态分布的随机数10个
a = np.random.randint()    #生成随机整数

查看数组类型

type(a)

查看数组中的数据类型

a.dtype

查看数组中元素数目

a.size

数组操作

#求和
np.sum()
#最大值
np.max()
#最小值
np.min()
#均值
np.mean()
#标准差
np.std()
#排序
np.sort()
#返回从小到大的排列在数组中的索引位置
np.argsort()

2.Pandas

基于numpy的一种工具,为解决数据分析任务创建,纳入大量库和一些标准的数据模型,提供了高效的操作大量数据集所需工具,大量便携处理数据的函数和方法。

导入pandas库

import pandas as pd

(1)Series

一维数组,与numpy中array,python中list类似

初始化

s = pd.Series([1,3 5,4,6,8])

索引

#行标签
s.index
#值
s.values
#切片
s[2:5]

(2)DataFrame

二维表格型数据结构,要求每一列数据格式相同

初始化

df = pd.DataFrame(np.random.randn(6,4))   #生成6行4列随机数组
#默认情况下,若不指定index参数和colums值将用从0开始的数字替代
#除了向DataFrame中传入二维数组,还可使用字典传入数据

查看数据

#头
df.head()
#尾
df.tail()
#下标
df.index()
#列标
df.columns()
#数据值
df.values()

读取数据及数据操作

#读入excel表
df = pd.read_excel()   #读取什么形式文件read_后就写什么
#添加行
df.append()
#删除行列
df.drop()

缺失值及异常值处理

缺失值

df.dropna()     #根据标签中缺失值进行过滤,删除缺失值
df.isnull()     #返回一个布尔值对象,判断哪些值是缺失值
df.notnull()    #isnull的否定式
df.fillna()     #填充缺失值

异常值

数据集中存在的不合理的值,数量很少,在不影响整体分布的情况下可以直接删除

基本统计分析

#描述性统计
df.describe()    #对df中的数值型数据进行描述性统计
#最大值
df.max()
#最小值
df.min()
#均值
df.mean()
#中值
df.median()
#方差
df.var()
#标准差
df.std()
#求和
df.sum()
#相关系数
df.corr()
#协方差
df.cov()

3.Matplotlib

python二维图形包,包含一系列类似matlab中绘图函数的相关函数,每个matplotlib.pyplot中的函数对当前图像进行一些修改,matplotlib.pyplot会自动记住当前图像和绘图区域,即直接在当前图像上作用。

导入matplotlib包

import matplotlib.pyplot as plt

显示图像

默认情况下,matplotlib.pyplot不会直接显示图像

plt.show()

绘制图像

plt.plot()

子图

plt.figure(num)    #产生一个指定编号为num的图

下面是使用禁忌搜索算法选取符合规定的坐标进行重心法计算的MATLAB代码: ```matlab % 22个点的坐标 points = [-0.54, 2.38; 0.05, 2.41;0.12,1.21;0.22,3.12;0.82,2.28;0.78,-1.98;1.42,6.72;1.52,5.48;1.38,5.02;1.41,4.53;1.98,2.62;1.78,1.83;1.82,0.74;2.91,1.78;3.52,-0.82;3.62,3.18;3.71,-0.21;4.18,1.85;4.25,1.12;4.03,-2.02;5.02,2.82;6.32,-0.54]; % 固定的三个点的坐标 A = [1.34, -1.18]; B = [1.72, 1.32]; C = [3.75, 1.95]; % 初始点x为22个点的重心 x = [mean(points(:,1)), mean(points(:,2))]; % 禁忌表 tabuList = []; % 目标函数的初始值 f = inf; % 禁忌搜索的参数设置 maxIter = 100; % 最大迭代次数 tabuTenure = 5; % 禁忌长度 for iter = 1:maxIter % 计算22个点到x的距离 dist = sqrt(sum((points - x).^2, 2)); % 判断是否符合规定 isFeasible = dist < sqrt(sum((points - A).^2, 2)) & ... dist < sqrt(sum((points - B).^2, 2)) & ... dist < sqrt(sum((points - C).^2, 2)); % 计算目标函数值 fNew = sum(min([dist, sqrt(sum((points - A).^2, 2)), sqrt(sum((points - B).^2, 2)), sqrt(sum((points - C).^2, 2))], [], 2)); % 更新禁忌表 if fNew < f tabuList = [tabuList; find(~isFeasible)]; else tabuList = [tabuList(2:end); find(~isFeasible)]; end % 去除禁忌表中的重复元素 tabuList = unique(tabuList); % 选择下一个点作为新的x dist(isFeasible) = inf; % 将可行点的距离设为无穷大 [~, idx] = min(dist); % 选择距离最近的非禁忌点 xNew = points(idx,:); % 更新目标函数值和x f = fNew; x = xNew; % 更新禁忌表中各元素的禁忌长度 for i = 1:length(tabuList) if tabuList(i) ~= idx tabuTenureList(tabuList(i)) = tabuTenureList(tabuList(i)) - 1; end end % 将新的禁忌元素加入禁忌表 tabuList = [tabuList, idx]; tabuTenureList(idx) = tabuTenure; % 更新禁忌表中各元素的禁忌长度 tabuTenureList = tabuTenureList - 1; tabuList(tabuTenureList <= 0) = []; tabuTenureList(tabuTenureList <= 0) = []; % 输出当前迭代次数和目标函数值 fprintf('Iteration %d: f = %f\n', iter, f); end % 输出最终结果 fprintf('The optimal location is (%f, %f).\n', x(1), x(2)); ``` 上述代码中,我们首先将初始点x设为22个点的重心,然后进行禁忌搜索。在每次迭代中,我们计算22个点到x的距离,并判断是否符合规定。如果符合规定,则认为这个点是可行的。然后,我们计算目标函数值,更新禁忌表,选择下一个点作为新的x,并更新禁忌表中各元素的禁忌长度。最终输出最优的选址地点。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值