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;
        }
    };
  • 相关阅读:
    php大文件分片上传
    ckeditor粘贴上传图片
    视频断点续传+java视频
    php上传文件夹 ​
    批量下载
    PHP上传超大文件解决方案
    js大文件上传
    java+web文件的上传和下载代码
    Webupload+PHP上传大文件
    【hdu1280】前M大的数
  • 原文地址:https://www.cnblogs.com/NeilZhang/p/5344016.html
Copyright © 2011-2022 走看看