1.两个数组的交集
给定两个数组nums1和nums2,返回它们的 交集。输出结果中的每个元素一定是唯一的。我们可以不考虑输出结果的顺序。
ps:set可直接去重
class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { set<int> s1(nums1.begin(),nums1.end()); set<int> s2(nums2.begin(),nums2.end()); vector<int> v; auto it1 = s1.begin(); auto it2 = s2.begin(); while(it1!=s1.end() && it2!=s2.end()) { if(*it1<*it2) it1++; else if(*it1>*it2) it2++; else if(*it1==*it2) { v.push_back(*it1); it1++; it2++; } } return v; } };2.带环链表
给定一个链表的头节点head,返回链表开始入环的第一个节点。如果链表无环,则返回null。
如果链表中有某个节点,可以通过连续跟踪next指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数pos来表示链表尾连接到链表中的位置(索引从 0 开始)。如果pos是-1,则在该链表中没有环。注意:pos不作为参数进行传递,仅仅是为了标识链表的实际情况。
eg:
输入:head = [3,2,0,-4], pos = 1输出:返回索引为 1 的链表节点解释:链表中有一个环,其尾部连接到第二个节点。
class Solution { public: ListNode *detectCycle(ListNode *head) { set<ListNode*> s; ListNode* cur = head; while(cur) { auto ret = s.insert(cur); if(ret.second == false) { return cur; } cur = cur->next; } return nullptr; } };思路:1.将链表节点的地址存入set中,使用set特性(若插入值已存在则插入失败)
2.insert返回类型为pair<迭代器,bool> 即 插入成功:返回<新插入节点地址,true>
插入失败:返回<已存在的节点的地址,false>
3.若ret.second == false说明该地址节点已经存在,插入失败,为带环链表
若ret.second == true说明该节点与之前节点并不重复,若该情况直至结束,则说明该链表不为带环链表
3.随机链表复制
class Solution { public: Node* copyRandomList(Node* head) { map<Node*,Node*> nodeMap; Node* copyhead = nullptr; Node* copytail = nullptr; Node* cur = head; while(cur) { if(copytail == nullptr) { copyhead = copytail = new Node(cur->val); } else { copytail->next = new Node(cur->val); copytail = copytail->next; } nodeMap[cur] = copytail; cur = cur->next; } Node* copy = copyhead; cur = head; while(cur) { if(cur->random == nullptr) { copy->random = nullptr; } else { copy->random = nodeMap[cur->random]; } cur = cur->next; copy = copy->next; } return copyhead; } };思路:1.nodeMap[cur] = copytail; 利用map的kv结构建立映射
2.copy->random = nodeMap[cur->random];即用cur->random当nodeMap的key查找出来的val赋给copy的random,从而实现随机链表的赋值。
4.前k个高频词
class Solution { public: struct Compare { bool operator()(const pair<string,int>& x,const pair<string,int>& y) { return x.second>y.second || ((x.second==y.second) && x.first<y.first); } }; vector<string> topKFrequent(vector<string>& words, int k) { map<string,int> countmap; for(auto& e:words) { countmap[e]++; } vector<pair<string,int>> v(countmap.begin(),countmap.end()); sort(v.begin(),v.end(),Compare()); vector<string> strv; for(int i = 0;i<k;i++) { strv.push_back(v[i].first); } return strv; } };