zoukankan      html  css  js  c++  java
  • LeetCode 1.TwoSum(哈希)

    两种方法

    • 先排序,然后前后夹逼(复杂度n*log(n))。
    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            int s = nums.size();
            pair<int,int>par[s];
            for(int i=0; i<s; ++ i)
            {
                par[i].first = nums[i];
                par[i].second = i;
            }
            sort(par, par+s);
            
            int b = 0, e = s - 1;
            
            while(b < e)
            {
                if(par[b].first + par[e].first > target)
                    e --;
                else if(par[b].first + par[e].first < target)
                    b ++;
                else
                {
                    if(par[b].second > par[e].second)
                        swap(b, e);
                    return vector<int>{par[b].second, par[e].second};
                }
            }
        }
    };
    
    • 存在unordered_map,然后直接find.(复杂度n)
    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            unordered_map<int, int>mp;
            for(int i=0; i<nums.size(); ++i)
                mp[nums[i]] = i;
            for(int i=0; i<nums.size(); ++ i)
            {
                int t = target - nums[i];
                if(mp.find(t) != mp.end() && mp[t] > i)
                {
                    return vector<int>{i, mp[t]};
                }
            }
        }
    };
    
  • 相关阅读:
    一本通1559跳跳棋
    一本通1558聚会
    一本通1555【例 4】次小生成树
    P1880 [NOI1995]石子合并
    P2066 机器分配
    P2073 送花
    P1886 滑动窗口
    P1637 三元上升子序列
    P1533 可怜的狗狗
    P1631 序列合并
  • 原文地址:https://www.cnblogs.com/aiterator/p/6494439.html
Copyright © 2011-2022 走看看