C++刷题(杂)

手撕系列

堆排

#include <iostream>
using namespace std;

void max_heapify(int ch[], int n, int i) {
	int l = 2 * i + 1; 
	int r = 2 * i + 2;
	int maxi = i;

	if (l < n && ch[maxi] < ch[l])
		maxi = l;
	if (r < n && ch[maxi] < ch[r])
		maxi = r;

	if (maxi != i) {
		int temp = ch[i];
		ch[i] = ch[maxi];
		ch[maxi] = temp;

		max_heapify(ch, n, maxi);
	}
}

void build_max_heap(int ch[], int n) {
	for (int i = n / 2 - 1; i >= 0; i--) {
		//n/2-1为最后一个非叶子结点的下标,从n/2-1到1可以保证左右儿子为根(也就是除开叶子结点)的二叉树都是最大堆
		max_heapify(ch, n, i);
	}
}

void heap_sort(int ch[], int n) {
	build_max_heap(ch, n);

	for (int i = n-1; i >= 1; i--) {
		int temp = ch[i];
		ch[i] = ch[0];
		ch[0] = temp;
		max_heapify(ch, i, 0);
	}
}

int main() {
	int n, ch[99];
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> ch[i];
	}
	heap_sort(ch, n);

	for (int i = 0; i < n; i++)
		cout << ch[i] << endl;
	return 0;
}

快排

#include <iostream>
using namespace std;

template<class T>
void Swap(T &a, T &b) {
	T c(a);
	a = b;
	b = c;
}

int Partition(int data[], int len, int l, int r) {
	int k = l - 1;
	for (int index = l; index < r; index++) {
		if (data[index] < data[r]) {
			k++;
			if (k != index)
				Swap<int>(data[k], data[index]);
		}
	}

	k++;
	Swap<int>(data[k], data[r]);

	return k;
}

void QuickSort(int data[], int len, int l, int r) {
	if (data == nullptr || len <= 0 || l < 0 || r >= len || l == r)
		return;

	int index = Partition(data, len, l, r);
	if (index > l)
		QuickSort(data, len, l, index - 1);
	if (index < r)
		QuickSort(data, len, index + 1, r);
}


int main(){
	int data[] = { 3,5,1,11,2,4,5,99,7,4,2 };
	QuickSort(data, 11, 0, 10);
	for (int i = 0; i < 11; i++)
		cout << data[i] << endl;
	return 0;
}

//第k小
int findK(int* ch, int k, int l, int r) {
	int tmp = Partition(ch, l, r);
	//cout << "tmp= " << tmp << endl;
	if (tmp == k-1)
		return ch[k-1];
	else if (tmp > k-1) {
		return findK(ch, k, l, tmp - 1);
	} else
		return findK(ch, k-tmp, tmp + 1, r);
}

归并(递归版本)

void Merge(vector<int>& num, int l, int r) {
	int mid = (l + r) >> 1;
	int pl = mid;
	int pr = r;
	int ptemp = r;
	vector<int> temp(num);

	while (pl >= l && pr >= mid+1) {
		if (num[pl] > num[pr]) {
			temp[ptemp--] = num[pl--];
		}
		else {
			temp[ptemp--] = num[pr--];
		}
	}

	while (pl >= l)
		temp[ptemp--] = num[pl--];

	while (pr >= mid + 1)
		temp[ptemp--] = num[pr--];

	for (int i = l; i <= r; i++) {
		num[i] = temp[i];
	}
}

void MergeSort(vector<int>& num, int l, int r) {
	if (l >= r)
		return;

	int mid = (l+r) >> 1;
	MergeSort(num, l, mid);
	MergeSort(num, mid + 1, r);
	Merge(num, l, r);
}



int main() {
	vector<int> hh{ 1,2,55,2,4,6, 6, 4, 2, 7, 53, 6};

	MergeSort(hh, 0, hh.size()-1);
	for (int i = 0; i < hh.size(); i++) {
		cout << hh[i] << " ";
	}
	return 0;
}

LCA

1.二叉树为搜索二叉树

直接计算就行了
从树的根节点开始和两个节点作比较

  • 如果当前节点的值比两个节点的值都大,则这两个节点的最近公共祖先节点一定在该节点的左子树中,则下一步遍历当前节点的左子树;
  • 如果当前节点的值比两个节点的值都小,则这两个节点的最近公共祖先节点一定在该节点的右子树中,下一步遍历当前节点的右子树;
  • 这样直到找到值是两个输入节点之间的值的节点,该节点就是两个节点的最近公共祖先节点。
2.二叉树为普通二叉树,有二叉树节点中包含指向父节点的指针

直接把从叶子结点到根看成是一条链,直接遍历,相当于寻找链表的第一个公共结点。详情看:两个链表的第一个公共结点。长的先走n步直到和短的一样长。

3.二叉树为普通二叉树
struct BinaryNode {
	BinaryNode* _left;
	BinaryNode* _right;
	BinaryNode* _parent;
	int _value;

	BinaryNode(const int& value)
		:_value(value)
		, _left(NULL)
		, _right(NULL)
		, _parent(NULL) {
	}
};

BinaryNode* GetLastCommonAncestor(BinaryNode* root, BinaryNode* node1, BinaryNode* node2) {
	if (root == NULL || node1 == NULL || node2 == NULL)
		return NULL;

	if (node1 == root || node2 == root)
		return root;

	BinaryNode * curNode;
	BinaryNode* lnode = GetLastCommonAncestor(root->_left, node1, node2);
	if (lnode != NULL) {
		/*这里是要解决LCA是为祖孙关系,此时返回本结点。
		 a
		/ \
		b  c
	   /\  
	   d e
	   设求b,d的lca,此时遍历到b返回,回到a则会遍历一遍b的左右结点,处理了lca是祖孙关系。
		*/
		curNode = GetLastCommonAncestor(lnode->_left, node1, node2);
		if(curNode == NULL)
			curNode = GetLastCommonAncestor(lnode->_right, node1, node2);
		if ((curNode == node1 && lnode == node2) || (curNode == node2 && lnode == node1))
			return root;
	}

	BinaryNode* rnode = GetLastCommonAncestor(root->_right, node1, node2);
	if (rnode != NULL) {
		curNode = GetLastCommonAncestor(rnode->_left, node1, node2);
		if (curNode == NULL)
			curNode = GetLastCommonAncestor(rnode->_right, node1, node2);
		if ((curNode == node1 && rnode == node2) || (curNode == node2 && rnode == node1))
			return root;
	}

	if (lnode && rnode)
		return root;

	if (lnode)
		return lnode;

	return rnode;
}

BitMap

在C/C++中int类型有4个字节,也就是32位。当我们有1000万条不同数据时,我们只需要1000万个位来表示(用下标标识),也就是10000000/(8*1024*1024) MB,大约为1.25MB。

class BitMap {
public:
    BitMap(int num):n(num),
                    mask(0x1F),//31
                    shift(5),//等于/32
                    pos(1<<mask),//<<31
                    a(1+n/32,0){}

    void set(int i) {//将位图中的第i位设置为1
        a[i>>shift] |= (pos>>(i & mask));//i&mask等于i%32
    }

    int get(int i) {//判断位图的第i位是否为1
        return a[i>>shift] & (pos>>(i & mask));
    }

    void clr(int i) {//将位图中的第i位设置为0
        a[i>>shift] &= ~(pos>>(i & mask));     
    }   
    
private:
    int n;
    const int mask;
    const int shift;
    const unsigned int pos;
    vector<unsigned int> a;
};

简化路径

给定一个文件的绝对路径(Unix-style),请进行路径简化。

Unix中, . 表示当前目录, … 表示父目录。

结果必须以 / 开头,并且两个目录名之间有且只有一个 /。最后一个目录名(如果存在)后不能出现 / 。你需要保证结果是正确表示路径的最短的字符串。

Example
样例 1:

输入: “/home/”
输出: “/home”
样例 2:

输入: “/a/./…/…/c/”
输出: “/c”
解释: “/” 没有上级目录, “/…/” 的结果就是 “/”.
Notice
你是否考虑了 路径为 “/…/” 的情况?

在这种情况下,你需返回"/"。

此外,路径中也可能包含双斜杠’/’,如 “/home//foo/”。

在这种情况下,应该忽略多余的斜杠,返回 “/home/foo”。

class Solution {
public:
	string simplifyPath(string &path) {
		path += '/';
		string nowPath = "";
		stack<string> st;
		for (int i = 0; i < path.length(); i++) {
			if (path[i] == '/') {
				if (nowPath == "..") {
					if (!st.empty()) {
						st.pop();
					}
				} else if (nowPath == ".") {
					;
				} else if (nowPath.length() > 0) {
					st.push(nowPath);
				}
				nowPath = "";
			} else {
				nowPath += path[i];
			}
		}

		string ans = "";
		while (!st.empty()) {
			ans = "/" + st.top() + ans;
			st.pop();
		}
		if (ans.length() == 0) {
			ans = "/";
		}

		return ans;
	}
};

LRU缓存机制

class LRUCache {
	struct node {
		int key, value;
	};
	int maxSize;
	list<node> cacheList;
	map<int, list<node>::iterator> mp;

public:
	LRUCache(int k) :maxSize(k) { }

	int get(int key) {
		map<int, list<node>::iterator >::iterator it = mp.find(key);
		if (it == mp.end()) {
			return -1;
		}
		list<node>::iterator listIt = mp[key];
		node n;
		n.key = key;
		n.value = listIt->value;
		cacheList.erase(mp[key]);
		cacheList.push_front(n);
		mp[key] = cacheList.begin();
		return cacheList.begin()->value;
	}

	void put(int key, int value) {
		map<int, list<node>::iterator >::iterator it = mp.find(key);
		if(it == mp.end()){
            if( cacheList.size() == maxSize){
                mp.erase(cacheList.back().key);
			    cacheList.pop_back();
            }
		} else {
			cacheList.erase(mp[key]);
		}
		node n;
		n.key = key;
		n.value = value;
		cacheList.push_front(n);
		mp[key] = cacheList.begin();
	}
};

设计模式

单例

懒汉,经典加锁+自动回收

class Singleton {
public:
	static Singleton* getInstance();

	// 实现一个内嵌垃圾回收类    
	class Fun {
	public:
		~Fun() {
			if (Singleton::p != NULL)
				delete p;
		}
	};

private:
	Singleton() { cout << "!" << endl; };
	
	static mutex m;
	static Singleton* p;
	static Singleton::Fun f;
};

Singleton::Fun f;
mutex Singleton::m;
Singleton* Singleton::p = NULL;
Singleton* Singleton::getInstance() {
	if (p == NULL) {
		m.lock();
		if (p == NULL) {
			p = new Singleton();
		}
		m.unlock();
	}
	return p;
}

懒汉,静态局部变量实现,不会在堆上new,避免自己回收资源

class Singleton {
public:
	static Singleton& getInstance() {//返回引用避免临时对象拷贝构造p
		static Singleton p;
		return p;
	}

private:
	Singleton() { cout << "!" << endl; };
};

饿汉模式,线程安全

class Singleton {
public:
	static Singleton* getInstance() {
		return p;
	}

private:
	Singleton() { cout << "!" << endl; };

	static Singleton* p;
};
Singleton* Singleton::p = new Singleton();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值