leetcode876
给定一个带有头结点 head 的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
class Solution
{
public:
ListNode* middleNode(ListNode* head) {
if(head == NULL)
return NULL;
if(head->next == NULL)
return head;
ListNode* fast, *slow;
fast = slow = head;
while(fast != NULL && fast->next != NULL) {
fast = fast->next->next;
slow = slow->next;
}
return slow;
}
};
这是快慢指针的经典解法,通过快慢指针移动速度的不同,来寻找到链表的中间结点,而最好的速度比为2:1,这样就可以使得当快指针到达链表尾的时候,慢指针刚好到达链表的中间结点,最后则可返回慢指针,即链表的中间结点。
也还有其他的方法,但是不太好,比如说利用辅助数组以及数组下标来获得
leetcode1290
位运算,result<<1就相当于result*2,result|=1(result|=0)相当于result++(不变)同时考虑到题中条件为节点不超过30个,不需要用long long int ,int 足矣。
class Solution
{
public:
int getDecimalValue(ListNode* head) {
if(head==NULL) return -1;
int result=0;
ListNode *p=head;
while(p!=NULL){
result=result<<1;
result|=p->val;
p=p->next;
}
return result;
}
};
leetcode面试题02.01
class Solution
{
public: //方法1:
ListNode* removeDuplicateNodes(ListNode* head) {
if (head == nullptr)
return head;
//第一个节点不会删除
unordered_set<int> set;
set.insert(head->val);
//从第二个节点开始删除
ListNode* prev = head;
while (prev->next) {
if (set.find(prev->next->val) != set.end()) //值重复 {
prev->next = prev->next->next; }
else //值首次出现 {
set.insert(prev->next->val);
prev = prev->next;
}
}
return head;
}
//方法2:
ListNode* removeDuplicateNodes(ListNode* head) {
if (head == nullptr)
return head;
ListNode* cur = head;
while (cur) {
ListNode* prev = cur;
while (prev->next) //遍历到链表尾,删除值等于cur->val的所有节点 {
if (prev->next->val == cur->val) {
prev->next = prev->next->next; }
else {
prev = prev->next;
}
}
cur = cur->next;
}
return head;
}
};
1、使用hashset保存首次出现的值 时间复杂度O(N)、空间复杂度O(N)
2、删除当前节点后面的值等于它的所有节点 时间复杂度O(N^2)、空间复杂度O(1)