您好,登錄后才能下訂單哦!
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
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。