203. 移除链表元素
遍历链表呗
本题的难点在于,头节点是有值的,所以处理头节点的问题需要解决
我的代码是
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
while(head!=nullptr&&head->val==val)
{
head=head->next;
}
if(head==nullptr)
return head;
ListNode* cur=head;
while(cur->next!=nullptr)
{
if(cur->next->val==val&&cur->next->next!=nullptr)
cur->next=cur->next->next;
else if(cur->next->val==val&&cur->next->next==nullptr)
cur->next=nullptr;
else
cur=cur->next;
}
return head;
}
};
hin慢hin慢,28ms
不过不同的测试用例测出来的速度也有所不同
然后我发现原来new ListNode(0,head)就是创建一个指向head的空指针啊
这就好办了
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
struct ListNode* dummyHead = new ListNode(0, head);
struct ListNode* temp = dummyHead;
while (temp->next != NULL) {
if (temp->next->val == val) {
temp->next = temp->next->next;
} else {
temp = temp->next;
}
}
return dummyHead->next;
}
};
205. 同构字符串
嗯不会
维护两张哈希表,第一张哈希表 s2t 以 s 中字符为键,映射至 t 的字符为值,第二张哈希表 t2s 以 t 中字符为键,映射至 s 的字符为值。从左至右遍历两个字符串的字符,不断更新两张哈希表,如果出现冲突(即当前下标 index 对应的字符 s[index] 已经存在映射且不为 t[index] 或当前下标 index 对应的字符 t[index] 已经存在映射且不为 s[index])时说明两个字符串无法构成同构,返回 false。
class Solution {
public:
bool isIsomorphic(string s, string t) {
unordered_map<char, char> s2t;
unordered_map<char, char> t2s;
int len = s.length();
for (int i = 0; i < len; ++i) {
char x = s[i], y = t[i];
if ((s2t.count(x) && s2t[x] != y) || (t2s.count(y) && t2s[y] != x)) {
return false;
}
s2t[x] = y;
t2s[y] = x;
}
return true;
}
};
map中的count方法:如果在映射容器中存在带有键K的元素,则该函数返回1。如果容器中不存在键为K的元素,则返回0