LeetCode 之 Two Sum — C++ 实现
来源:互联网 发布:centos没有桌面 编辑:程序博客网 时间:2024/06/05 06:05
Two Sum
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
函数返回这两个数的索引,index1 必须小于 index2。注意,返回的索引不是从 0 开始的。
假设对于每个输入只有一个解。
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
分析:
使用 map,键为数组值,值为数组索引。用target减去数组值,然后在 map 中查找这个差值,如果存在,则返回两个索引;不存在,将此数组值存入 map 中,重复此过程指导查找完数组为止。
class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { if(nums.empty())//空 { return vector<int>(); } map<int, int> addend; int numsSize = nums.size(); for(int index = 0; index < numsSize; ++index) { if(addend.find(target - nums[index]) == addend.end())//另一个加数不在 map 中,加入 map { addend[nums[index]] = index + 1; } else //找到两个合法的数 { vector<int> ret; ret.push_back(addend[target - nums[index]]); ret.push_back(index + 1); return ret; } } return vector<int>(); }};
0 0
- LeetCode 之 Two Sum — C++ 实现
- [LeetCode]1 Two Sum(C++,Python实现)
- 【Leetcode】【Python】【C++】1. Two Sum实现
- LeetCode-1-Two Sum(C语言实现)
- LeetCode 1. Two Sum(c语言实现)
- javascript实现leetcode之two sum
- leetCode之Two Sum python实现
- leetcode之Two Sum
- LeetCode 之 Two Sum
- LeetCode之Two Sum
- LeetCode之Two Sum
- leetcode之two Sum
- leetcode之Two Sum
- leetcode 之Two Sum
- LeetCode 之 Two Sum
- LeetCode之Two Sum
- leetcode之two sum
- Leetcode之Two Sum
- AT NEW 用法和注意
- 【编程习题★★★☆☆】等式变换求解
- Java 中利用 axis2 进行webservice 客户端编写
- 第十五周 程序阅读二
- ARM R0-R16
- LeetCode 之 Two Sum — C++ 实现
- 114Flatten Binary Tree to Linked List 二叉树到单链表的扁平化处理
- ABAP中操作回车、换行、回车加换行、的方案
- openssl 自定义生成证书和私钥并使用
- 如何编译&使用boost库?
- uploadify上传文件
- 一步步走进Android MaterialDesign 之 DrawerLayout
- Android Studio开发JNI工程
- Android Choreographer 源码笔记