程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 1. Two Sum,twosum

1. Two Sum,twosum

編輯:C++入門知識

1. Two Sum,twosum


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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

 

UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4        vector<int> ret(2,-1);
 5        
 6        unordered_map<int,int> myMap;
 7        
 8        for(int i = 0 ; i < nums.size(); i++){
 9            if(myMap.find(target-nums[i]) == myMap.end()){
10                myMap[nums[i]] = i;
11            }else{
12                ret[0] = myMap[target-nums[i]];
13                ret[1] = i;
14                return ret;
15            }
16        }
17        return ret;
18     }
19 };

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved