zoukankan      html  css  js  c++  java
  • 今天是第一次刷LeetCode,来此发表一下自己的方法,并进行打卡。第1天

    1、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, and you may not use the same element twice.

    大体意思是:给定一个int类型的数组和一个确定值,要求返回两个加和为确定值的数的下标。

    以下是结合答案和自己的思路给出的复杂度为O(n)的答案。

     1 class Solution {
     2 public:
     3     vector<int> twoSum(vector<int>& nums, int target) 
     4     {
     5         
     6         vector<int> temp;
     7         unordered_map<int,int> num;//哈希表
     8         int t,i;
     9         //建立哈希表填充数值,每一个数值对应其下标
    10         for(i = 0;i < nums.size();i ++)
    11         {
    12             num[nums[i]] = i;
    13         }
    14         for(i = 0;i < nums.size();i ++)
    15         {
    16             t = target - nums[i];根据一个数值求得另一个数值
    17             if(num.find(t) != num.end() && num[t] > i)//判断t是否存在并判断下标是否比i小避免重复
    18             {
    19                             //返回两个下标
    20                 temp.push_back(i);
    21                 temp.push_back(num[t]);
    22             }
    23 
    24         }
    25         return temp;
    26         
    27     }
    28 };                        
  • 相关阅读:
    去除文件中的空行
    数据分析 numpy matplotlib
    程序员
    c#
    java
    微信小游戏
    小游戏开发手册
    模板
    微信小程序小程序代码构成(.json .js .wxss .wxml)
    微信程序
  • 原文地址:https://www.cnblogs.com/jiandanqinxin/p/8556903.html
Copyright © 2011-2022 走看看