☰
【c++】LeetCode:1. Two Sum
2026/10/23 1:02:02 网站建设 项目流程

问题描述:Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.
给定一个数组和一个目标值,找到两个数组相加的和为目标值.只有一个解,不能够使用两次相同的元素.

LZ的想法比较简单,两次循环,好暴力…

class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> indice_a; for(int i = 0; i<nums.size()-1; i++){ for(int j = i+1; j<nums.size(); j++){ if(nums[i]+nums[j]==target) { indice_a.push_back(i); indice_a.push_back(j); break; } } } return indice_a; } };

结果测试时间是216ms!

为了减少runtime,也即时间复杂度

使用哈希表,只要10ms!

class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { std::unordered_map<int, int> mp; std::vector<int> ans; // 用哈希表来做 for(int i = 0; i < nums.size(); i ++) // 对于数组中的每个数据 { // 判断target - numbers[i]在不在 if(mp.count(target - nums[i])) // 如果在里面 { // 那么numbers中就存在两个数和为target ans.push_back(mp[target - nums[i]] ); ans.push_back(i ); break; } if(mp.count(nums[i]) != 1) { mp[nums[i]] = i; } } return ans; } };

代码的魅力在于此_

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询