LeetCode-5

350. 两个数组的交集 II

思路

  1. 两个map分别统计在两个数组中一个元素的出现次数
  2. 把其中一个数组排序去重,然后查询两个map
  3. 取这个元素在两个数组里出现次数的最小值n,往ans里面push该元素n次

AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
map<int, int> v,n;
vector<int> ans;
for (int x : nums1) {
v[x]++;
}
for (int x : nums2) {
n[x]++;
}
sort(nums1.begin(), nums1.end());
nums1.erase(unique(nums1.begin(), nums1.end()), nums1.end());
for (int x : nums1) {
if (v[x] && n[x]) {
int l = v[x] > n[x] ? n[x] : v[x];
for (int i = 0; i < l; i++)
ans.push_back(x);
}
}
return ans;
}
};

大佬思路

阅读更多

LeetCode-9

92. 反转链表 II

思路

  1. 两个指针a、b,分别找到被反转的第一个结点的前一个结点,被反转的结点的最后一个结点,(在开头设置一个哑结点,防止被反转的第一个结点是头结点)
  2. 再来一个指针c,保存被反转的最后一个结点的next,然后把最后一个结点的next设为null
  3. 反转链表,然后把新链表的head接回去,把c接回到末尾
  4. 返回哑结点的next,不能返回head,因为反转以后,head有可能不是head了

AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode* dummy = new ListNode(0), *a, *b, *c;
dummy->next = head;
a = b = c = dummy;
for (int i = 0; i < m - 1; i++) {
a = a->next;
b = b->next;
}
for (int i = 0; i < n - m + 1; i++) {
b = b->next;
}
c = b->next;
b->next = NULL;
a->next = reverseList(a->next);
while (a->next != NULL) {
a = a->next;
}
a->next = c;
return dummy->next;
}
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) return head;
ListNode *temp = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return temp;
}
};

15. 三数之和

阅读更多