zoukankan      html  css  js  c++  java
  • 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].

    1/ 首先想到的是 通过两次循环去寻找 这两个数,找到后立刻返回。

    但是当提交运行的时候,会报错,运行时间过长。    

    2/ 想到的另一种方法是,先通过排序(nlgn),然后通过两个指针去前后遍历数组(n)

    3/ 最后一种方法在网上看到的,因为自己对hashmap并不是很熟悉。一下贴出网上的hashmap的代码

    class Solution {
        public:
    vector<int> twoSum(vector<int> &numbers, int target) {
            vector<int> res;
            int length = numbers.size();
            map<int,int> mp;
            int find;
            for(int i = 0; i < length; ++i){
            // if have target-numbers[i] return target-numbers[i] ,else create a target-numbers[i] element 
                find=mp[target - numbers[i]]; 
                if( find ){
                    res.push_back(find);
                    res.push_back(i+1);
                    break;
                }
                mp[numbers[i]] = i;
            }
            return res;
        }
    };
  • 相关阅读:
    js 数组相减
    js 对象数组去重
    vue 首次不触发watch的解决方法
    "神药"推荐--紫花地丁
    openstack 平台添加 nvidia vGPU
    string易错点整理总结
    CentOS安装图形界面
    CentOs安装ssh和scp
    数组把0移到末尾
    Windows下Celery安装与下使用
  • 原文地址:https://www.cnblogs.com/NeilZhang/p/5344016.html
Copyright © 2011-2022 走看看