LeetCode OJ:Two Sum(兩數之和)

來源:互聯網
上載者:User

標籤:

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

給一個vector,一個value,要求求出vector之內的兩數相加之和等於value的兩個index。

這裡的基本思想是用一個map先來儲存vector元素的值與他們對應的index,然後迴圈vector,用value減去每個數之後,把差值直接放到map裡面去尋找
看能不能找到對應的index,大體上就是這個思想,下面詳見代碼:

 1 class Solution { 2 public: 3     vector<int> twoSum(vector<int>& nums, int target) { 4         map<int, int> index; 5         vector<int> result; 6         int sz = nums.size(); 7         for (int i = 0; i < sz; ++i){ 8             index[nums[i]] = i; 9         }10         map<int, int>::iterator it;11         for (int i = 0; i < sz; ++i){12             if ((it = index.find(target - nums[i])) != index.end()){13                 if (it->second == i) continue;//這一步要注意,防止找到的index與當前的i是相等的14                 result.push_back(i + 1);15                 result.push_back(it->second + 1);16                 break;17             }18         }19         return result;20     }21 };

 

LeetCode OJ:Two Sum(兩數之和)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.