zoukankan      html  css  js  c++  java
  • leetcode 练习1 two sum

        leetcode 练习1  two sum

                whowhoha@outlook.com

    问题描述

    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:暴力破解法: O(n^2) runtime, O(1) space – Brute force: The brute force approach is simple. Loop through each element x and find if there is another value that equals to target – x. As finding another value requires looping through

    the rest of array, its runtime complexity is O(n^2).

     

    解法2:使用HashMap。把每个数都存入map中,然后再逐个遍历,查找是否有 target – nums[i]。  O(n) runtime  O(n) space,

    vector<int> twoSum(vector<int>& nums, int target){

           vector<int> vec;

           map<int,int> m;

           for (int i = 0; i < nums.size(); i++)

           {

                  if(m.find(target - nums[i]) != m.end())

                  {

                         vec.push_back(m[target - nums[i]] );

                         vec.push_back(i);

                         break;

                  }

                  m[nums[i]] = i;

           }

           return vec;

    }

    调用:

           int a[6]={2,7,1,8,9};

           vector<int> vec(a,a+5);

           vector <int> vect= twoSum(vec,15);

           return 1;

  • 相关阅读:
    富文本编辑器 ueditor
    防抖和节流 lodash插件
    lodash
    awesome
    怎么在移动端模拟pc端进行web开发调试日志
    添加水印
    node.js取参四种方法req.body,req.params,req.param,req.body
    插件包
    python——Scrapy框架简介、内置选择器、管道文件、爬虫模块中的spider类
    python——BeautifulSoup4解析器,JSON与JsonPATH,多线程爬虫,动态HTML处理
  • 原文地址:https://www.cnblogs.com/whowhoha/p/5738282.html
Copyright © 2011-2022 走看看