题目来源:
leetcode题目,网址:110. 平衡二叉树 - 力扣(LeetCode)
解题思路:
哈希表。遍历链表若当前元素在哈希表中,则将其删除,否则将其加入哈希表。
解题代码:
- /**
- * Definition for singly-linked list.
- * struct ListNode {
- * int val;
- * ListNode *next;
- * ListNode(int x) : val(x), next(NULL) {}
- * };
- */
- class Solution {
- public:
- ListNode* removeDuplicateNodes(ListNode* head) {
- if(head==nullptr){
- return head;
- }
- unordered_set<int> set;
- set.insert(head->val);
- ListNode* res=head;
- while(head->next!=nullptr){
- if(set.find(head->next->val)!=0){
- head->next=head->next->next;
- }else{
- set.insert(head->next->val);
- head=head->next;
- }
- }
- return res;
- }
- };
总结:
不使用临时缓存区,只想到暴力遍历一种 方法。
官方题解给出了哈希表和两重循环(暴力遍历)两种解法。