• 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;

  • 相关阅读:
    2003开机自动登陆然后马上锁定计算机
    修改DNS、网关的VBS代码,不需重起即时生效
    页面自动刷新代码
    dos命令给权限
    无法运行VBS代码
    去掉2003或2kserver版的系统启动报错
    让易语言的信息框总在最前
    教你轻松搞定RJ45网线接头
    小技巧:如何设定永久通用WinRAR压缩密码
    Bootstrap入门教程
  • 原文地址:https://www.cnblogs.com/whowhoha/p/5738282.html
Copyright © 2020-2023  润新知