1. Two Sum

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].
題目大意:
在一個數組中找出2個元素的和等于目標數,輸出這兩個元素的下標。
思路:
最笨的辦法嘍,雙循環來處理。時間復雜度O(n*n)。
代碼如下:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
int i,j;
for(i = 0; i < nums.size();i++)
{
for(j = i+1; j < nums.size();j++)
{
if(nums[i] + nums[j] == target)
{
result.push_back(i);
result.push_back(j);
break;
}
}
}
return result;
}
};參考他人的做法:https://discuss.leetcode.com/topic/3294/accepted-c-o-n-solution
采用map的鍵值,把元素做鍵,把元素的下標做值。
vector<int> twoSum(vector<int> &numbers, int target)
{
//Key is the number and value is its index in the vector.
unordered_map<int, int> hash;
vector<int> result;
for (int i = 0; i < numbers.size(); i++) {
int numberToFind = target - numbers[i];
//if numberToFind is found in map, return them
if (hash.find(numberToFind) != hash.end()) {
result.push_back(hash[numberToFind]);
result.push_back(i);
return result;
}
//number was not found. Put it in the map.
hash[numbers[i]] = i;
}
return result;
}2016-08-11 15:02:14
另外有需要云服務器可以了解下創新互聯scvps.cn,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業上云的綜合解決方案,具有“安全穩定、簡單易用、服務可用性高、性價比高”等特點與優勢,專為企業上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。
新聞標題:leetCode1.TwoSum數組-創新互聯
文章路徑:http://www.yijiale78.com/article4/ceieoe.html
成都網站建設公司_創新互聯,為您提供品牌網站建設、網站收錄、營銷型網站建設、品牌網站制作、電子商務、App設計
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯