leetcode刷题记录-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.

解题思路:

利用target减去数组中每个数得到数组的差值数组,以原题中的例子为例:{2,7,11,15}对应的差值数组为{7,2,-1,,6},然后遍历原数组,若差值数组中也包含这个数且对应索引不相等,则返回原数组该值索引与差值数组中的索引。为了让时间复杂度为O(n),差值数据需用哈希map的方式保存。

解题源码:

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4         map<int, int> finder;
 5         int index1 = -1;
 6         int index2 = -1;
 7         for(int i=0; i<nums.size(); ++i){
 8             int _num = target - nums[i];
 9             finder.insert(map<int, int>::value_type(_num, i));
10         }
11         for(int i=0; i<nums.size(); ++i){
12             map<int, int>::iterator itr;
13             itr = finder.find(nums[i]);
14             if (itr!=finder.end()){
15                 int j = finder[nums[i]];
16                 if (i!=j){
17                     index1 = min(i, j);
18                     index2 = max(i, j);
19                     break;
20                 }
21             }
22         }
23         vector<int> rst;
24         rst.push_back(index1+1);
25         rst.push_back(index2+1);
26         return rst;
27     }
28 };

 

转载于:https://www.cnblogs.com/leemo-o/p/4990024.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值