1. 程式人生 > 實用技巧 >1. 兩數之和

1. 兩數之和

1. 題目描述:

給定一個整數陣列 nums和一個目標值 target,請你在該陣列中找出和為目標值的那兩個整數,並返回他們的陣列下標。

你可以假設每種輸入只會對應一個答案。但是,陣列中同一個元素不能使用兩遍。

示例:

給定 nums = [2, 7, 11, 15], target = 9

因為 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/two-sum

2. 解題思路

2.1 暴力法(C++)--不推薦

  用兩個for迴圈遍歷所有可能,時間複雜度為O(n^2)。

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4         int i, j;
 5         for(i = 0; i < nums.size()-1; i++) {
 6             for(int j = i + 1; j < nums.size(); j++) {
 7                 if((nums[i] + nums[j]) == target){
 8                     return
{i, j}; 9 } 10 } 11 } 12 return {}; 13 } 14 };

2.2 一遍hash(C++)--推薦

  在容器中插入元素的同時,檢查容器中是否存在差值。

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4         map<int, int> temp; // map<key, value>
5 vector<int> current(2, 0); // 儲存結果,初始化一個大小為2,值為0的容器。 6 for(int i=0;i<nums.size();i++){ 7 if(temp.count(target-nums[i])>0){ // 在temp中查詢target-nums的個數, 8 // 大於0表示 9 current[0] = temp[target-nums[i]]; // 儲存第一個數的key 10 current[1] = i; // 儲存第二個key 11 break; 12 } 13 temp[nums[i]] = i; // 將前面所有不符合條件的都放入map, 14 // key為nums值,value為下標。 15 } 16 return current; 17 } 18 };

3. 結語

  努力去愛周圍的每一個人,付出,不一定有收穫,但是不付出就一定沒有收穫! 給街頭賣藝的人零錢,不和深夜還在擺攤的小販討價還價。願我的部落格對你有所幫助(*^▽^*)(*^▽^*)!

  如果客官喜歡小生的園子,記得關注小生喲,小生會持續更新(#^.^#)(#^.^#)。