• 今天是第一次刷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 };                        
  • 相关阅读:
    PS选区认识
    移动工具
    PS认识及新建文件
    第02组 Alpha冲刺(3/4)
    第02组 Alpha冲刺(2/4)
    第02组 Alpha冲刺(1/4)
    第02组 团队Git现场编程实战
    第二次结对编程作业
    团队项目-需求分析报告
    团队项目-需求分析报告
  • 原文地址:https://www.cnblogs.com/jiandanqinxin/p/8556903.html
Copyright © 2020-2023  润新知