zoukankan      html  css  js  c++  java
  • LeetCode0001.两数之和

    题目要求

    算法分析

    暴力算法,双循环迭代,即可找到满足条件的数组下标,时间复杂度为O(n2)。

    优化算法,可以利用哈希表(C#用字典)在第一次迭代时先存储数组的数据,

    这样第二次迭代检索数据时可以利用索引快速查找,实现了用空间换时间。

    更优算法,不必要先存储再查找,可以边存数据,边查找。

    代码展示(C#)

     1 public class Solution {
     2     public int[] TwoSum(int[] nums, int target) {
     3         var dic = new Dictionary<int, int>();
     4         for(int i = 0; i < nums.Length; i++)
     5         {
     6             if (!dic.ContainsKey(nums[i]))
     7             {
     8                 dic.Add(nums[i], i);
     9             }
    10         }
    11         for(int i = 0; i < nums.Length; i++)
    12         {
    13             int n = target - nums[i];
    14             if (dic.ContainsKey(n) && dic[n] != i)
    15             {
    16                 return new int[2] { i, dic[n] };
    17             }
    18         }
    19         return null;
    20     }
    21 }

    代码展示(C++)

     1 class Solution {
     2 public:
     3     vector<int> twoSum(vector<int>& nums, int target) {
     4         unordered_map <int, int > map;
     5         vector<int> res;
     6         for (int i = 0; i < nums.size(); i++) {
     7             int n = target - nums[i];
     8             if (map.find(n) != map.end()) {
     9                 res.push_back(map[n]);
    10                 res.push_back(i);
    11                 break;
    12             }
    13             else {
    14                 map[nums[i]] = i;
    15             }
    16         }
    17         return res;
    18     }
    19 };

    提交结果

  • 相关阅读:
    CentOS8下安装mysql8
    Git使用
    《操作系统导论》读书笔记
    《Linux命令行大全》读书笔记
    Centos8 开机后显示 Activate the web console with: systemctl enable --now cockpit.socke
    numpy学习笔记
    CentOS8使用阿里源
    Python 面向对象
    matplotlib解决不显示中文问题
    MySQL基础第三课
  • 原文地址:https://www.cnblogs.com/KingR/p/12927324.html
Copyright © 2011-2022 走看看