Time Limit Exceeded /** * Definition for singly-linked list. * struct ListNode { * int…
- User
Time Limit Exceeded
/**
-
Definition for singly-linked list.
-
struct ListNode {
-
code
int val; -
code
ListNode *next; -
code
ListNode() : val(0), next(nullptr) {} -
code
ListNode(int x) : val(x), next(nullptr) {} -
code
ListNode(int x, ListNode *next) : val(x), next(next) {} -
}; / class Solution { public: ListNode mergeKLists(std::vector<ListNode*>& lists) { if (lists.empty()) { return nullptr; } ListNode* linked_list = lists[0]; ListNode* head = linked_list; int i = 0; for (int i = 1; i < lists.size(); i++) { ListNode* node = lists[i];
codewhile (node != nullptr) { if (linked_list->val == node-> val) { int k = node-> val; add_element(linked_list, k); linked_list = linked_list-> next; node = node->next; } else if(linked_list->val <= node->val && (linked_list->next == nullptr || node->val < linked_list->next->val)) { int k = node-> val; add_element(linked_list, k); linked_list = linked_list-> next; node = node->next; } } linked_list = head; } return linked_list;}
void add_element(ListNode* linked_list, int k) { ListNode* new_node = new ListNode; new_node->val = k; new_node->next = linked_list->next; linked_list->next = new_node; } };
-
- Assistant
The current solution is causing a time limit exceeded error because it doesn't correctly merge the linked lists. The inner while loop doesn't account for the case when the value of the current node in the second linked list is greater than all the values in the first linked list.
To fix this issue, you can modify the code as follows:
cpp - User
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode next) : val(x), next(next) {} * }; / class Solution { public: ListNode mergeKLists(std::vector<ListNode>& lists) { if (lists.empty()) { return nullptr; } ListNode linked_list = lists[0]; ListNode* head = linked_list; for (int i = 1; i < lists.size(); i++) { ListNode* node = lists[i]; while (node != nullptr) { if (linked_list->val == node-> val) { int k = node-> val; add_element(linked_list, k); linked_list = linked_list-> next; node = node->next; } else if(linked_list->val <= node->val && (linked_list->next == nullptr || node->val < linked_list->next->val)) { int k = node-> val; add_element(linked_list, k); linked_list = linked_list-> next; node = node->next; } } linked_list = head; } return linked_list; } void add_element(ListNode* linked_list, int k) { ListNode* new_node = new ListNode(k); new_node->next = linked_list->next; linked_list->next = new_node; } }; на русском Time Limit Exceeded
- Assistant
Текущее решение вызывает ошибку "Time Limit Exceeded", потому что оно неправильно объединяет связанные списки. Внутренний цикл while не учитывает случай, когда значение текущего узла во втором связанном списке больше всех значений в первом связанном списке.
Чтобы исправить эту проблему, вы можете изменить код следующим образом:
cpp - User
Line 38: Char 19: runtime error: member access within null pointer of type 'ListNode' (solution.cpp) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:47:19
/**
-
Definition for singly-linked list.
-
struct ListNode {
-
code
int val; -
code
ListNode *next; -
code
ListNode() : val(0), next(nullptr) {} -
code
ListNode(int x) : val(x), next(nullptr) {} -
code
ListNode(int x, ListNode *next) : val(x), next(next) {} -
}; / class Solution { public: ListNode mergeKLists(std::vector<ListNode*>& lists) { if (lists.empty()) { return nullptr; } ListNode* new_node = new ListNode();
priority_queue que; std::vector vct; for(auto& list : lists) { while(!(list == nullptr)) { que.push(list->val); list = list->next; } }
while(!que.empty()) { vct.push_back(que.top()); que.pop(); } int i = 0; while(i < vct.size()) { new_node->val = vct[i]; new_node = new_node->next; i++; }
-
- Assistant
Программа вызывает ошибку времени выполнения "undefined behavior" потому, что присваивается nullptr указателю new_node->next, и затем пытается обратиться к этому nullptr, выходя за пределы допустимого поведения программы.
Чтобы исправить эту ошибку, измените код, чтобы создать новый узел и сохранить его ссылку в другой указатель, который не будет изменяться в процессе присваивания значений узлов:
cpp