LeetCode 01. 两数之和
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 01. 两数之和
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
原題
分析:
1.根據題意,首先需要將要數據選擇一個合適的 數據結構模型。? 因為是對應相關聯,所以我們選擇unordered_map
2.因為是一組數,所以用數組 ,將數值與數組下標對應起來
3.已知兩數之和,從數組第一個數開始比較,確認余數是否在unordered_map中,如果存在,則使用key值取出其value;如果不在,則以key - value的形式將當前值和當前下表存入unordered_map,然后繼續重復執行。
4.將要兩個下標傳入vector即可
class Solution { public:vector<int> twoSum(vector<int>& nums, int target) {vector<int> res;unordered_map<int,int> hash;for (int i = 0; i < nums.size(); i ++ ){int another = target - nums[i];if (hash.count(another)){res = vector<int>({hash[another], i});break;}hash[nums[i]] = i;}return res;}};總結
以上是生活随笔為你收集整理的LeetCode 01. 两数之和的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 南京房屋租赁登记备案证明需要什么材料(南
- 下一篇: 剑指 Offer 51-----59