首页 > 编程语言 > 详细

(C++練習) 1. Two Sum

时间:2019-02-26 22:31:46      阅读:196      评论:0      收藏:0      [点我收藏+]

題目 :

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 sameelement twice.

大意 :

給一個 integer array 在裡頭找出指定的總和數, 找出2個數的index

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target)
 4     {
 5         unordered_map<int, int> mapping;
 6         vector<int> result;
 7 
 8         for (int i = 0; i < nums.size(); i++)
 9         {
10             mapping[nums[i]] = i;
11         }
12 
13         for (int i = 0; i < nums.size(); i++)
14         {
15             const int gap = target - nums[i];
16             if (mapping.find(gap) != mapping.end() && mapping[gap] > i)
17             {
18                 result.push_back(i);
19                 result.push_back(mapping[gap]);
20                 break;
21             }
22         }
23 
24         return result;
25     }
26 };

16行有用到一些 unodered_map相關函數, 其中 find會回傳 interator 意思是會回傳一個

相同型別的資料變數, 則 end 也會回傳一個 interator 但是這個 interator 是最後一個key之後的一個位置。

假設判斷這個key存不存在可以用 count or map[key] return 0, 但表不存在

        mapping.find(15);
        mapping.end();
        mapping.count(2);

 

(C++練習) 1. Two Sum

原文:https://www.cnblogs.com/ollie-lin/p/10440478.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!