[Leetcode] Two Sum (C++)


我在Github上新建了一個解答Leetcode問題的Project, 大家可以參考, 目前是Java 為主,里面有leetcode上的題目,解答,還有一些基本的單元測試,方便大家起步。

題目:

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

Tag:

Array; Hash Table

體會:

啊哈哈,這道題一次成功,雖然版本跟下面這個不一樣,但是思路是一樣的。

這個題很巧妙的用了map,因為是找兩個數湊起來能是target, 所以遇到一個數,你就知道了它應該和誰去湊對,雖然不知道能湊對的這個數是否在array中存在又或者存在在什么地方。搞一個<number, index>的map, 記錄每個數字出現的位置。逐個去檢查數字,看看他要湊成對的那個數字是不是已經存在了即可。

P.S. 我的map里直接存的是要去找的那個數。比如target=9, 現在在位置0遇到了2,那我就存一個map[9-2]=0,然后檢查的時候就可以直接去keys里面找有沒有7了。

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int> &numbers, int target) {
 4             int n = numbers.size();
 5             vector<int> result;
 6             map<int, int> index;
 7             for (int i = 0; i < n; i++) {
 8                 if (index.count(numbers[i]) != 0) {
 9                     // if exists
10                     result.push_back(index[numbers[i]] + 1);
11                     result.push_back(i + 1);
12                     break;
13                 } 
14                 index[target - numbers[i]] = i; 
15             }
16             return result;
17     }
18 };

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM