Day 3
容器(vector)作为函数参数如何传参
void 函数名( vector< int>* pobj );
void 函数名( const vector< int>* pobj ); // 在函数内不能改变 pobj 指向的对象 ,//调用时不会调用拷贝构造函数
void 函数名( vector< int>& obj );
void 函数名( const vector< int>& obj ); // 在函数内不能改变 obj 对象,// 在函数调用时调用了vector的拷贝构造函数
分别对应
其对应的调用分别是:
deal( vec );
deal( &vec );
deal( &vec );
deal( vec );
deal( vec );
size
vector 的size函数返回vector大小,返回值类型为size_type,Member type size_type is an unsigned integral type,即无符号整数;
ector A;A.size()-1因为size返回值是无符号类型所以 A.size()-1越界,是个很大的数所以要用的时候要么预先定义一个 int n = A.size() - 1;或者int(A.size() - 1)或者int(A.size()) - 1或者
static_cast(A.size())
resize
vv.resize(int n,element)表示调整容器vv的大小为n,扩容后的每个元素的值为element,默认为0
resize()会改变容器的容量和当前元素个数
resize(),设置大小(size);
reserve(),设置容量(capacity);
size()是分配容器的内存大小,而capacity()只是设置容器容量大小,但并没有真正分配内存
剑指 Offer 35. 复杂链表的复制
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个
random 指针指向链表中的任意节点或者 null。示例 1:
输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出:[[7,null],[13,0],[11,4],[10,2],[1,0]] 示例 2:输入:head = [[1,1],[2,1]] 输出:[[1,1],[2,1]] 示例 3:
输入:head = [[3,null],[3,0],[3,null]] 输出:[[3,null],[3,0],[3,null]] 示例 4:
输入:head = [] 输出:[] 解释:给定的链表为空(空指针),因此返回 null。
提示:
-10000 <= Node.val <= 10000 Node.random 为空(null)或指向链表中的节点。 节点数目不超过 1000 。
*/
class Solution {
public:
unordered_map <Node*,Node*> encoder;
Node* copyRandomList(Node* head) {
if(head == nullptr){
return nullptr;
}
if (!encoder.count(head)){
Node* now =new Node(head->val);
encoder[head] = now;
now->next = copyRandomList(head->next);
now->random = copyRandomList(head->random);
}
return encoder[head];
}
};