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個元素的和等于目標數,輸出這兩個元素的下標。
思路:
最笨的辦法嘍,雙循環(huán)來處理。時間復雜度O(n*n)。
代碼如下:
class Solution { public: vectortwoSum(vector & nums, int target) { vector 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的鍵值,把元素做鍵,把元素的下標做值。
vectortwoSum(vector &numbers, int target) { //Key is the number and value is its index in the vector. unordered_map hash; vector 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
另外有需要云服務器可以了解下創(chuàng)新互聯scvps.cn,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。