LeetCode1_Two Sum

微信图片.dat文件解密实战:用Python一键转PNG(附完整代码) 本文详细介绍了如何通过Python解密微信图片.dat文件并转换为PNG格式的完整教程。文章深入解析了微信.dat文件的异或加密原理,提供了自动检测密钥的Python脚本,并分享了批量解密和性能优化的实用技巧,帮助用户轻松恢复和整理微信聊天图片。 阅读详情
My answer

第三遍提交

<span style="font-weight: bold;">   </span> /**
     * running time : O(n)
     */
    public int[] twoSum(int[] numbers, int target) {
        int[] result = new int[2];
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        
        int size = numbers.length;
        for(int i=0; i<size; i++){
            int curr = numbers[i]; 
            if(!map.containsKey(curr)){
                map.put(target - curr, i);
            }else{
                result[0] = map.get(curr) + 1;
                result[1] = i+1;
               break;
            }
        }
        
       return result; 
    }
第一遍提交

<strong>  </strong> /**
     * running time is O(n^2)
     * 返回结果 Time Limit Exceeded
     * LeetCode使用的测试用例,是超长的数组
     * Last executed input: [0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,....]
     * 
     * 教训: 程序不能只是正确性,还要考虑效率。
     */
    public int[] twoSumVersion1(int[] numbers, int target) {
        int[] result = new int[2];
        
        for(int i=0; i<numbers.length; i++){
            int rightOperand = target - numbers[i];

            for(int j=i+1; j<numbers.length; j++){
                if(rightOperand == numbers[j]){
//                    Please note that your returned answers (both index1 and index2) are not zero-based.
                    result[0] = i+1;
                    result[1] = j+1;
                    return result;
                }
            }
        }
        return result;
    }

Summary

1.     1st answer is O(n^2)

      The two-layer loops algorithm is first idea for most people. However, the running time is O(n^2), which means it might be not be used in real application.

2.     2nd answer based on Hash Map; store all elements on Hash Map.

      Disadvantage: This algorithm needs a very big space to store elements in hash map. Most of elements are not the output concerns.

3.     3rd answer based on Hash Map; only store the examined elements on Hash Map.

     3.1   the output order is not a matter

     3.2   For-loop keeps one output. 

深度学习工具包 DeepLearningToolbox 深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge") 立即下载

相关推荐

从零到一:手把手教你用STM32F103C8T6打造个人专属开发板(附立创EDA工程与源码)

本文详细介绍了如何使用STM32F103C8T6微控制器从零开始设计和制作个人专属开发板。内容涵盖硬件选型、原理图设计、PCB布局、功能验证等全流程,并提供了立创EDA工程文件和源码,帮助开发者深入理解STM32开发板的硬件架构与设计要点。

weixin_26802933的博客 285

Leetcode算法系列二(链表)

1.8道经典链表常考题目 例1-a:反转链表 例1-b:反转链表2 例2:链表求交点 例3:链表求环 例4:链表划分 例5:复杂链表的复制 例6-a:2个排序链表归并 例6-b:K个排序链表归并 206.反转链表 反转一个单链表。 示例: 输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL 进阶: 你可以迭代或递归地反转链表。你能否用两种方法解决这道题? public class Solution {

weixin_44337475的博客 511

GNSS接收机性能测试指标详解:TTFF、位置精度、灵敏度等关键参数如何评估

本文详细解析了GNSS接收机性能测试的关键指标,包括首次定位时间(TTFF)、位置精度、灵敏度等,帮助工程师系统评估接收机性能。通过多频段协同定位和载波相位测试等技术,提升定位精度至亚米级。同时,介绍了灵敏度测试的极限挑战和授时精度的专业测试方案,为GNSS接收机的性能优化提供实用指导。

cuda7parallel的博客 963

Leetcode1-两数之和详解

本文主要讲解了使用暴力法和哈西表法计算Leetcode中两个数之和的题目。

白羊by的博客 1728

GX WORKS2通过交换机连接PLC的方法

三菱PLC连接方法的分享

weixin_64927621的博客 3619

SAP SD核心流程解析:从销售订单到财务结算的实战指南

本文深入解析SAP SD模块从销售订单到财务结算的核心流程,重点剖析了销售订单中的行项目类别如何作为流程的“总开关”,决定了后续交货、开票及财务集成的走向。文章结合实战案例,详细拆解了正常销售、退货、第三方销售、寄售等典型流程的配置要点与国内化适配方案,并阐述了SD与财务模块集成的关键连接点,为顾问和用户提供了一份全面的实战指南。

weixin_29250403的博客 426

LeetCode第一题解答

简单描述:在一维数组中,找到与目标值相等的两个元素,并返回这两个元素的下标。

weixin_44254063的博客 658

R语言的下载、安装及环境配置(Rstudio&VSCode)

R for Windows是一个免费的用于统计计算和统计制图的优秀工具,是R语言开发工具。它拥有数据存储和处理系统、数组运算工具(其向量、矩阵运算方面功能尤其强大)、完整连贯的统计分析工具、优秀的统计制图等功能。提供的图形界面,可以在其中访问控制台、创建脚本或安装其他软件包。

zegeai的博客 2万+

1. 两数之和

由于哈希查找的时间复杂度为 O(1)O(1),所以可以利用哈希容器 map 降低时间复杂度 遍历数组 nums,i 为当前下标,每个值都判断map中是否存在 target-nums[i] 的 key 值 如果存在则找到了两个值,如果不存在则将当前的 (nums[i],i) 存入 map 中,继续遍历直到找到为止 如果最终都没有结果则抛出异常 classSolution{ publicint[]twoSum(int[]nums,inttarget){ Map&lt...

trhflybingo的博客 310

【论文速读】MLDT:基于开源大语言模型的复杂长时机器人任务规划多层次分解方法

—在数据驱动的人工智能技术领域,开源大语言模型(LLMs)在机器人任务规划中的应用是一个重要的里程碑。近期基于开源大语言模型的机器人任务规划方法通常利用大量的任务规划数据集来提升模型的规划能力。虽然这些方法展现出了一定的前景,但它们在处理复杂长时任务时存在困难,因为这类任务需要理解更多的上下文信息并生成更长的动作序列。本文提出多层次分解任务规划方法(MLDT)来解决这一局限性。该方法创新性地在目标级、任务级和动作级对任务进行分解,以应对复杂长时任务带来的挑战。

muyulingfengye的博客 1645

LLC型自驱动半桥谐振变换器:电压电流变化与自然换向解析

变换器的工作状态经历了多个阶段,从模态一的关断状态,到模态二和三的电流供电状态,每个阶段都得到了合理的设计和优化。的工作原理,尤其是在半个周期内的电压和电流变化。上图 展示了该变换器在工作时的电压和电流波形,它为我们揭示了变换器如何通过精确的电流和电压控制,优化性能并实现高效能转换。,并根据负载情况调整电流和电压的工作模式,能够极大提升变换器的效率,尤其是在零电压开通和自然换向的设计中,发挥着关键作用。这意味着,电流会随着时间周期的变化,呈现典型的振荡波形,从而达到良好的电流控制。是两个关键的电流变量。

weixin_43199439的博客 279

Leetcode—1.两数之和【简单】(unordered_map)

这个题是个简单题,但我这里先用C语言实现一下但是编译却出现问题我在自己的编译器上都运行得很好,后来我发现原来平台是有格式要求的,就得按他给的这个这上面注明了数组要被malloc一下,名称自拟以下是我的暴力破解法C代码,可以参考一下。

Atticus的博客 403

告警不是闹钟:AI 如何把告警过滤成真正的“求救信号”?

告警不是闹钟:AI 如何把告警过滤成真正的“求救信号”?

Echo_Wish 241

LeetCode 1 Two Sum题解

题目地址:https://leetcode.com/problems/two-sum/ 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 e

赞美月亮的专栏 665

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

Leetcode力扣 1 | 两数之和 Two Sum —— python

Leetcode力扣 1 | 两数之和 Two SumQuestionAnswerBrute Force 暴力求解法HashTable 哈希表法 该系列以提高编程能力、学习数据结构与算法为目的 编程语言:python Question 给定一个数组nums、一个目标target值(以下简写成nums、target) 我们的目的是在nums中,找到两个元素,使其相加等于target值,然后返回这两个元素在nums中的索引,就是数组下标。 题目中给了三个示例: 第一个返回下标0和1,因为2与7的和为9

idl1ng的博客 1140

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

LeetCode 1. Two Sum 题解

本题是算法的经典入门问题,主要考察对哈希表的理解和应用。通过使用哈希表,我们可以将时间复杂度从 O(n²) 降低到 O(n),大大提高了算法的效率。哈希表的核心思想是:通过哈希表来存储已经遍历过的元素及其下标,这样当我们遍历到当前元素时,可以在 O(1) 的时间复杂度内检查目标值与当前元素的差值是否已经存在于哈希表中。这种方法不仅适用于两数之和问题,还可以应用于许多其他需要快速查找元素的场景。掌握哈希表的使用,对于解决这类问题非常重要。

cannonjinx的博客 4192

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

[LeetCode] No.1 Two Sum

“做程序员太辛苦了,我想换行……我该怎么办?” “敲一下回车。” 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...

但行好事 莫问前程 348

力扣Leetcode1 | 两数之和(Two Sum)

暴力法、一次哈希表和两次哈希表法 https://blog.youkuaiyun.com/zhushaojiecumt/article/details/102846196 视频: https://www.bilibili.com/video/BV1Li4y1E7gT?p=1 双指针法 如果列表是无序的,需要先排序,使用双指针,分别指向头、尾。如果两数之和大于target,尾指针前移,如果两数之和小于target,首指针后移。 class Solution: def twoSum(self, nums: List

maoersong的专栏 358

Leetcode ☞ 1. Two Sum ☆ 【Hashmap】

给一数组和一target数,有两个元素的和为target。求这两个元素的下标的和。

Dr_Unknown的博客 983

Leetcode 1 Two Sum

Question : 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...

嗨~ 172

Leetcode 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...

Smiling_Wang的博客 267

LeetCode 1 Two Sum——在数组上遍历出花样

本文始发于个人公众号:TechFlow 今天是周末,和大家一起来看一道算法题。这道题是大名鼎鼎的LeetCode的第一题,也是面试当中非常常见的一道面试题。题目不难,但是对于初学者来说应该还是很有意思,也是一道很适合入门的算法题。 废话不多说,让我们一起来看看题目吧。 Given an array of integers, return indices of the two numbers su...

TechFlow的博客 230

java two sum 讲解_【LeetCode 力扣】1. Two Sum 两数之和 Java 解法

LeetCode的第一题,英文单词书中 Abandon 一般的存在,让我们来看一下题目:Given an array of integers, returnindicesof the two numbers such that they add up to a specific target.You may assume that each input would haveexactlyo...

weixin_36072221的博客 217

【LeetCode with JavaScript】1.Two Sum

原题网址:https://leetcode.com/problems/two-sum/ 难度:Easy 题目 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。 Example: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 ...

zwkkkk1的博客 1024

LeetCode 1.Two Sum map 初次使用Markdown*****

外传 经过室友推荐blog转战Markdown编辑,初次使用还觉得挺不方便需要那么多快捷键,不如鼠标点的快。今天这一篇文章才写一半就觉得很好用,就像电脑操作用鼠标点击和windows快捷键操作一样爽,在此向还没转战的朋友推荐,顺便练习自己的操作。 不方便的是代码高亮显示不好。 参考快速上手 记录插入链接格式 题目 题意 注意 思路1 代码

老夫编代码就是一把梭 1144

LeetCode力扣 1. 两数之和 Two Sum 题解代码 JavaScript

问题 https://leetcode-cn.com/problems/two-sum/ 练习使用JavaScript解答 /** * @param {number[]} nums * @param {number} target * @return {number[]} */ var twoSum = function(nums, target) { var i, j = nums.length-1, sum; var num2 = []; for(i=0;i&lt

Coding home - 漂流瓶jz 590
上一篇: LeetCode2_Add Two Numbers
下一篇: LeetCode3_Longest Substring Without Repeating Characters
cuidiwhere
博客等级 码龄19年 133粉丝 102原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值