剑指Offer读书笔记(2)

2.3数据结构

数组和字符串:用连续的内存存储数字和字符。

链表和树:因操作时会用到大量的指针,解决问题时留意代码的鲁棒性

栈:一个与递归紧密相关的数据结构。

队列:与广度优先遍历紧密相关

 

数组

时间复杂度为O(1),空间效率不高。

使用动态数组时,尽量减少改变容量大小的次数,减少时间上的消耗。

PSC/C++没有记录数组的大小,用指针访问时留意边界条件。

再用sizeof()求值时,数组名只有在单独出现的时候才代表整个数组,其他时候都表示为首元素或首元素的地址。

//二维数组中查找(从左到右从上到下增大)
//思路:选取右上角数进行比较,相等退出;如果右上角的数大于Key值则剔除该列;反之剔除该行
bool Find(int *matrix, int rows, int cols, int key)
{
	bool find = false;
	if (matrix != NULL && rows > 0 && cols > 0)
	{
		int row = 0;
		int col = cols - 1;
		while (row < rows && col >= 0)//row[),col[]
		{
			if (matrix[row*cols + col] == key)
			{
				find = true;
				break;
			}
			else if (matrix[row*cols + col] > key)
			{
				col--;
			}
			else
			{
				row++;
			}
		}
	}
	return find;
}

PS:多维数组在内存也是线性存储的,因此可用想象成一维数组,数组元素也为数组,如二维数组是数组元素为一维数组的数组,此时 数组首地址+n偏移地址将是以 n*sizeof(数组元素)偏移。

字符串

字符串是由若干个字符组成的序列。

C/C++中每个字符串的结尾都是以‘\0’作为结尾。

为节省内存,C/C++把常量字符串放到单独的一个内存区域。当几个指针赋值给相同的常量字符串时,它们实际上指向相同的内存地址。常量字符串赋值给不同的数组时情况于此不同。

void _tmain()
{
	char str1[] = "hello world";
	char str2[] = "hello world";


	char* str3 = "hello world";
	char* str4 = "hello world";


	if (str1 == str2)
		printf("str1==str2");
	else
		printf("str1!=str2");		//会被打印


	if (str3 == str4)
		printf("str3==str4");		//会被打印
	else
		printf("str3!=str4");
}
//空格替换为%20
//思路:反向由字符串尾开始遍历替换
//举一反三:A1,A2数组有序,A1内存足够将A2插入A1尾部并有序
//合并两个数组是发都可考虑右后向前移动
//时间复杂度为O(n)
void ReplaceBlank(char string[], int length)//length是为字符串开辟的数组空间长度int
{
	if (string != NULL || length <= 0)
	{
		return;
	}
	int OldLength = 0;//字符串原长度
	int NumBlank = 0;//记录空格数
	int i = 0;
	while (string[i] != '\0')
	{
		OldLength++;
		if (string[i] == ' ')
		{
			NumBlank++;
		}
		++i;
	}
	int NewLength = OldLength + NumBlank * 2;//空格替换后的字符长度
	if (NewLength > length)//判断字符空间是否足够
		return;
	int OldIndex = OldLength;
	int NewIndex = NewLength;//新字符串末尾的下标
	while (OldIndex >= 0 && NewIndex > OldIndex)//判断新字符串是否增长
	{
		if (string[OldIndex] == ' ')
		{
			string[NewLength] = '0';
			string[NewLength] = '2';
			string[NewLength] = '%';
		}
		else
		{
			string[NewLength--] = string[OldLength];
		}
		OldLength--;
	}
}


链表

链表是一种动态数据结构,因此创建时不需要知道链表的长度。当插入一个新节点时为节点分配内存,然后调整链表指针的指向。内存分配不是在创建链表时一次性完成,而是每次添加一个节点分配一次内存。因此链表的空间的效率比数组高。

//链表尾插
struct ListNode
{
	int data;
	ListNode* next;
};
void PushBack(ListNode** pHead, int value)//因为有可能改变头结点,所以用二级指针串头结点
{
	ListNode* pNew = new ListNode();
	pNew->data = value;
	pNew->next = NULL;
	if (*pHead == NULL)
	{
		*pHead = pNew;
	}
	else
	{
		ListNode* pNode = *pHead;
		while (pNode->next != NULL)
		{
			pNode = pNode->next;
		}
		pNode->next = pNew;
	}
}
void RemoveNode(ListNode** pHead, int value)
{
	if (pHead == NULL&&*pHead == NULL)
	{
		return;
	}
	ListNode* del = NULL;
	if ((*pHead)->data == value)
	{
		del = *pHead;
		*pHead = (*pHead)->next;
	}
	else
	{
		ListNode* pNode = *pHead;
		while (pNode->next != NULL && pNode->next->data != value)
		{
			pNode = pNode->next;
		}
		if (pNode->next != NULL&&pNode->next->data == value)//判断是遍历完链表还是找到目标节点
		{
			del = pNode->next;
			pNode->next = pNode->next->next;
		}
	}
	if (del != NULL)
	{
		delete del;
		del = NULL;
	}
}
//从尾到头打印链表
//思路:链表由尾到头打印的顺序类似于栈的后进先出,考虑用栈解决
void RePrintList(ListNode* pHead)
{
	stack<ListNode*> nodes;
	ListNode* pNode = pHead;
	while (pNode != NULL)
	{
		nodes.push(pNode);
		pNode = pNode->next;
	}
	while (!nodes.empty())
	{
		pNode = nodes.top();
		cout << pNode->data << " ";
		nodes.pop();
	}
}
void RePrintListR(ListNode* pHead)//递归可以看做是一个栈结构,因此可用递归解决
{
	if (pHead != NULL)
	{
		if (pHead->next != NULL)//递归存在的问题在于如果链表过长,栈开辟空间是可能会发生栈溢出
		{
			RePrintListR(pHead->next);
		}
		cout << pHead->data << " ";
	}
	cout << endl;
}

二叉树是树的一种特殊的数据结构。

二叉树的特例:二叉搜索树,堆和红黑数

最大堆中根节点的值最大。

最小堆中根节点的值最小。

红黑树的最长路径不超过最短路径的两倍。

STLset,multiset,map,multimp基于红黑树实现。

//重建二叉树
//根据前序遍历和后序遍历建立二叉树
//思路:将建立二叉树分为建立左,右子树的问题,发现两者本质上一样,问题简化为建立子树,可用递归完成
struct BinaryTreeNode
{
	int m_nValue;
	BinaryTreeNode* m_pLeft;
	BinaryTreeNode* m_pRight;
};
BinaryTreeNode* Construct(int* pre, int* inor, int length)
{
	if (pre == NULL || inor == NULL || length <= 0)
		return NULL;

	return ConstructCore(pre, pre + length - 1, inor, inor + length - 1);
}
BinaryTreeNode* ConstructCore(int* startPre, int* endPre, int* startInor, int* endInor)
{
	//前序遍历的第一个数是根节点值
	int rootValue = startPre[0];
	BinaryTreeNode* root = new BinaryTreeNode();
	root->m_nValue = rootValue;
	root->m_pLeft = root->m_pRight = NULL;

	if (startPre == endPre)
	{
		if (startInor == endInor&&*startPre == *startInor)
			return root;
		else
			throw std::exception("Invalid input.");
	}
	//在中序遍历中找到根节点值
	int* rootInor = startInor;
	while (rootInor <= endInor&&*rootInor != rootValue)
		++rootInor;

	if (rootInor == endInor&&*rootInor != rootValue)
		throw std::exception("Invalid input.");

	int leftLength = rootInor - startInor;
	int* leftPreorderEnd = startPre + leftLength;
	if (leftLength > 0)
	{
		//构建左子树
		root->m_pLeft = ConstructCore(startPre + 1, leftPreorderEnd, startInor, rootInor - 1);
	}
	if (leftLength < endPre - startPre)
	{
		//构建右子树
		root->m_pRight = ConstructCore(leftPreorderEnd + 1, endPre, rootInor + 1, endInor);
	}

	return root;
}
前序遍历序列的第一个数字便是根节点值,由此创建根节点,接下来在中序遍历序列中找到根节点的位置,这样就能确定左、右子树的节点数量。在前序遍历和后序遍历中划分了左右子树,以此重新建立二叉树。

栈和队列

实际应用中,操作系统会给每个线程创建一个栈用来存储函数调用各个函数的参数、返回地址及临时变量。

栈通常是一个不考虑排序的数据结构,需要O(n)时间找到栈中最大或最小的元素。

队列:先进先出,与广度优先遍历紧密联系,如二叉树的层序遍历。

//栈和队列
//利用两个栈构建一个队列(利用两个队列实现一个栈)
template <class T>
class CQueue
{
public:
	CQueue(void);
	~CQueue(void);

	void appendTail(const T& node);//
	T deleteHead();

private:
	stack<T> stack1;
	stack<T> stack2;
};
template <class T>
void CQueue::appendTail(const T& element)
{
	stack1.push(element);
}
template <class T>
T CQueue<T>::deleteHead()
{
	if (stack2.size() <= 0)
	{
		while (stack1.size() > 0)
		{
			T& data = stack1.top();
			stack1.pop();
			stack2.push(data);
		}
	}
	if (stack2.size() == 0)
		throw new exception("queue is empty");
	T head = stack2.top();
	stack2.pop();

	return head;
}

分配两个栈,stack1负责插入,stack2负责取队头。把stack1中的元素逐个弹出压入stack2中,元素在stack2中的顺序边和原来在stack1中的顺序相反。此时便与队列的元素弹出顺序相同。当stack2不为空时,在stack2中栈顶的元素是最先进入队列的元素,可以弹出;如果stack2为空时,我们把stack1中的元素逐个弹出压入stack2中。由于先进入队列的元素被压入stack1的低端,进过弹出和压入之后就处于stack2的栈顶,可以被弹出。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
【优质项目推荐】 1、项目代码均经过严格本地测试,运行OK,确保功能稳定后才上传平台。可放心下载并立即投入使用,若遇到任何使用问题,随时欢迎私信反馈与沟通,博主会第一时间回复。 2、项目适用于计算机相关专业(如计科、信息安全、数据科学、人工智能、通信、物联网、自动化、电子信息等)的在校学生、专业教师,或企业员工,小白入门等都适用。 3、该项目不仅具有很高的学习借鉴价值,对于初学者来说,也是入门进阶的绝佳选择;当然也可以直接用于 毕设、课设、期末大作业或项目初期立项演示等。 3、开放创新:如果您有一定基础,且热爱探索钻研,可以在此代码基础上二次开发,进行修改、扩展,创造出属于自己的独特应用。 欢迎下载使用优质资源!欢迎借鉴使用,并欢迎学习交流,共同探索编程的无穷魅力! 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值