复杂链表的复制
描述:
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点)。
代码:
/*
struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};
class Solution {
public:
RandomListNode* Clone_main(RandomListNode* pHead, int dep) {
if (pHead == NULL) return NULL;
RandomListNode *new_ptr = new RandomListNode(pHead->label);
new_ptr->next = Clone_main(pHead->next, dep+1);
old_ptr_to_id[pHead] = dep;
new_id_to_ptr[dep] = new_ptr;
return new_ptr;
}
void Clone_random(RandomListNode* pHead, RandomListNode* newHead) {
if (pHead == NULL) return;
int id = old_ptr_to_id[pHead->random];
newHead->random = new_id_to_ptr[id];
Clone_random(pHead->next, newHead->next);
}
map<RandomListNode*, int> old_ptr_to_id;
map<int, RandomListNode*> new_id_to_ptr;
RandomListNode* Clone(RandomListNode* pHead)
{
RandomListNode *new_ptr = Clone_main(pHead, 0);
old_ptr_to_id[NULL] = -1;
new_id_to_ptr[-1] = NULL;
Clone_random(pHead, new_ptr);
return new_ptr;
}
};
*/
Ugly Number
参考Poj 1338
用优先队列乱搞一下也行,不过在poj discuss里面发现了很溜的方法
我们可以设idx2,idx3,idx5是三个位于已经求出的Ugly Number中的指针,每次取最小的生成下一个Ugly Number后向后移动。唯一要注意的是会有重复的生成,需要判断一下。
class Solution {
public:
int GetUglyNumber_Solution(int index) {
if (index == 1) return 1;
vector<int> seq(index+1);
seq[0] = 1;
int idx2 = 0, idx3 = 0, idx5 = 0;
for (int i=1;i<=index-1;++i) {
seq[i] = min (seq[idx2] * 2, min (seq[idx3]*3, seq[idx5]*5));
if (seq[i] == seq[idx2] * 2) ++idx2;
if (seq[i] == seq[idx3] * 3) ++idx3;
if (seq[i] == seq[idx5] * 5) ++idx5;
}
return seq[index-1];
}
};
位运算模拟加法
最简单的方法,从低位到高位模拟,记录下进位
还有更流弊的方法,直接用异或和与两种操作。。。
int Plus (int lhs, int rhs) {
int cf = 0, ret = 0;
for (int i=0;i<32;++i) {
int a = (lhs>>i)&1, b = (rhs>>i)&1;
int new_cf = (a&b) | (a&cf) | (b&cf), bit = a^b^cf;
ret |= (bit << i);
cf = new_cf;
}
return ret;
}
求1+2+3+…+n
求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句
递归的思路很好想。。
这里还有几种开脑冻的做法。。。
class Solution {
public:
int dfs(int &sum, int n) {
sum += n;
return !n || dfs(sum, n-1);
}
int Sum_Solution(int n) {
int ret = 0;
dfs(ret, n);
return ret;
}
};
1076

被折叠的 条评论
为什么被折叠?



