leetcode第一題兩數之和擊敗了 98.11% 的用戶的答案(C++)

雖然題目簡單,但我這好不容易優化到前2%,感受也值得分享給你們(方法比較偷機)css

 

題目:數組

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

你能夠假設每種輸入只會對應一個答案。可是,你不能重複利用這個數組中一樣的元素。函數

示例:優化

來源:力扣(LeetCode)
連接:https://leetcode-cn.com/problems/two-sum
著做權歸領釦網絡全部。商業轉載請聯繫官方受權,非商業轉載請註明出處。spa

 

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

由於 nums[0] + nums[1] = 2 + 7 = 9
因此返回 [0, 1]blog

 

個人解答:內存

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4         vector<int> res(2);
 5         int endPos = nums.size();
 6         //vector內存是連續的 這裏直接取地址
 7         //這樣後面訪問時不須要調用vecotr的成員函數
 8         //由於不清楚編譯器優化級別
 9         int *numArr = &nums[0];
10 
11         if (endPos < 5)
12         {
13             //數組長度比較小時使用原始的雙循環法更快點
14             for (int i = 0; i < endPos; ++i)
15             {
16                 //遍歷數組,找出每一個元素與target之差作爲尋找目標
17                 int nNeed = target - numArr[i];
18                 for (int j = i + 1; j < endPos; ++j)
19                 {
20                     //在後面找,看有沒有與目標相同的數字
21                     if (numArr[j] == nNeed)
22                     {
23                         //若是有直接返回
24                         res[0] = i;
25                         res[1] = j;
26                         return res;
27                     }
28                 }
29             }
30         }
31 
32         //數組比較大時使用一次遍歷哈希查找的方法比較快
33         map<int, int> mpNums;
34         pair<map<int, int>::iterator, bool> pairRet;
35         //int numCurr;
36 
37         //遍歷數組
38         for (int i = 0; i < endPos; ++i)
39         {
40             //把當前數值當key,當前位置當value插入map
41             //numCurr = numArr[i]; //實驗發現這裏使用numCurr取值代替numArr[i]反而慢了
42             //看來讀取消耗遠低於寫
43             pairRet = mpNums.insert(make_pair(numArr[i], i));
44 
45             //若是插入成功(大部分狀況下是插入成功的)
46             if (pairRet.second)
47             {
48                 //查看map裏面是否有目前值-當前元素值的數據存在
49                 //若是有就說明找到目標
50                 int numNeed = target - numArr[i];
51                 map<int, int>::iterator it = mpNums.find(numNeed);
52                 if (it != mpNums.end() && it->second != i)
53                 {
54                     //題目要求不能重複使用本身,因此須要限制it->second != i
55                     res[0] = it->second;
56                     res[1] = i;
57                     return res;
58                 }
59             }
60             else
61             {
62                 //若是插入失敗說明
63                 //已經在map存在相同數值,則看它們加起來是否等於target
64                 if ((numArr[i] << 1) == target) //2 * numArr[i]
65                 {
66                     res[0] = pairRet.first->second;
67                     res[1] = i;
68                     return res;
69                 }
70             }
71         }
72 
73         res.clear();
74         return res;
75     }
76 
77 };

 

執行結果:
經過
執行用時 :8 ms, 在全部 cpp 提交中擊敗了98.11%的用戶
內存消耗 :10.1 MB, 在全部 cpp 提交中擊敗了37.46%的用戶
相關文章
相關標籤/搜索