// TwoNum.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <vector> #include <map> using namespace std; //Definition for singly-linked list. struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: vector<int> TwoSum(vector<int> nums, int target) { vector<int> res; const int len = nums.size(); map<int, int> mp; for (int i = 0; i < len;i++) { mp[nums[i]] = i; } map<int, int>::iterator it = mp.end(); for (int i = 0; i < len; i++) { it = mp.find(target - nums[i]); if (mp.end() != it && i != it->second) { res.push_back(i+1); res.push_back(it->second+1); break; } } return res; } ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode nodeTemp(INT_MIN); ListNode* pPre = &nodeTemp; ListNode* la = l1; ListNode* lb = l2; ListNode* pListNew = pPre; int flag = 0; for (; nullptr != la || nullptr != lb; la = (nullptr == la) ? nullptr : la->next, lb = (nullptr == lb) ? nullptr : lb->next, pListNew = pListNew->next) { ListNode* pNewNode = nullptr; const int a = (nullptr != la)? la->val : 0; const int b = (nullptr != lb) ? lb->val : 0; int value = (a + b + flag) % 10; flag = (a + b + flag) / 10; printf("value:%d flag:%d\n", value, flag); pNewNode = new ListNode(value); pListNew->next = pNewNode; } if (flag > 0) { pListNew->next = new ListNode(flag); } return pPre->next; } }; int main() { #if 0 vector<int> vec = { 3,2,4 }; Solution s; vector<int> res = s.TwoSum(vec, 6); for (auto item : res) { printf(" %d\n", item); } #endif // 0 ListNode a1(1); ListNode a2(8); //ListNode a3(4); a1.next = &a2; //a2.next = &a3; ListNode b1(0); //ListNode b2(22); //ListNode b3(8); //b1.next = &b2; //b2.next = &b3; ListNode* la = &a1; ListNode* lb = &b1; Solution s; ListNode* pResult = s.addTwoNumbers(la, lb); while (pResult) { ListNode* pDelNode = pResult; printf("node: %d\n", pDelNode->val); pResult = pResult->next; delete pDelNode; pDelNode = nullptr; } return 0; }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Browser-use 详细介绍&使用文档
· 软件产品开发中常见的10个问题及处理方法
· Vite CVE-2025-30208 安全漏洞