main.cpp Güncelle
This commit is contained in:
parent
f2376f7a40
commit
958d567cb7
40
main.cpp
40
main.cpp
@ -1,17 +1,37 @@
|
|||||||
#include <vector>
|
/**
|
||||||
#include <unordered_map>
|
* 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 {
|
class Solution {
|
||||||
public:
|
public:
|
||||||
std::vector<int> twoSum(std::vector<int>& nums, int target) {
|
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
|
||||||
std::unordered_map<int, int> num_map; // Stores number and its index
|
ListNode dummy(0); // Dummy node to simplify result list creation
|
||||||
for (int i = 0; i < nums.size(); ++i) {
|
ListNode* p = &dummy; // Pointer to build the new list
|
||||||
int complement = target - nums[i];
|
int carry = 0; // To track the carry from additions
|
||||||
if (num_map.find(complement) != num_map.end()) {
|
|
||||||
return {num_map[complement], i}; // Found the two indices
|
while (l1 != nullptr || l2 != nullptr || carry) {
|
||||||
|
int sum = carry;
|
||||||
|
if (l1 != nullptr) {
|
||||||
|
sum += l1->val; // Add value from l1 if not reached its end
|
||||||
|
l1 = l1->next; // Move to the next node in l1
|
||||||
}
|
}
|
||||||
num_map[nums[i]] = i; // Store index of the current number
|
if (l2 != nullptr) {
|
||||||
|
sum += l2->val; // Add value from l2 if not reached its end
|
||||||
|
l2 = l2->next; // Move to the next node in l2
|
||||||
|
}
|
||||||
|
|
||||||
|
carry = sum / 10; // Calculate the carry
|
||||||
|
p->next = new ListNode(sum % 10); // Create a new node with the digit value
|
||||||
|
p = p->next; // Move pointer to the newly created node
|
||||||
}
|
}
|
||||||
return {};
|
|
||||||
|
return dummy.next; // Return the result linked list
|
||||||
}
|
}
|
||||||
};
|
};
|
Loading…
Reference in New Issue
Block a user