【LeetCode】1. Two Sum

输入一个正整数n,输出一个最小正整数m,使得m的各位乘积等于n /* 1.:编写一个函数func,输入一个正整数n,返回一个最小的正整数m,使得m的各位乘积等于n,例如输入100.输出455,输入36,输出49 */#if 0 int func(int n) { int num=0; int s; int m[10]={0}; int p=0;//数组m的下标 int sum=n; int i=2;//1~81 阅读详情

1. Two Sum

Easy

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

1. 使用HashMap记录元素和所在位置。

2. 检索vector中每一个元素值m[i],通过HashMap查找是否有target-m[i]的元素存在且不与本身重复。

3. 如果存在,记录并退出。

#include<iostream>
#include<vector>
#include<map>
using namespace std;
vector<int> twoSum(vector<int>& nums, int target) {
	map<int,int> m;    //数值+位置 
	vector<int> ans;
	for(int i=0;i<nums.size();i++){
		m[nums[i]]=i;
	}
	for(int i=0;i<nums.size();i++){
		int t = target - nums[i];
		if(m.count(t)&&m[t]!=i){
			ans.push_back(i);
			ans.push_back(m[t]);
			break;
		}
	}
	return ans;
}
int main(void){
	int n,elem,target;vector<int> input;
	while(cin>>n>>target){
		if(!input.empty()) input.pop_back();
		for(int i=0;i<n;i++){
			cin>>elem;
			input.push_back(elem);
		}
		vector<int> ans = twoSum(input,target);
		cout<<ans[0]<<" "<<ans[1]<<endl;
	}
	return 0;
}

 

告别卡顿!在RK3588上优化Gstreamer推拉流与RKNN推理的完整Pipeline实战 本文详细介绍了在RK3588平台上优化Gstreamer推拉流与RKNN推理的全链路Pipeline实战。通过解码环节参数调优、RKNN线程管理、内存预分配策略以及编码输出优化,实现60FPS流畅处理与亚秒级延迟。特别针对实时视频分析场景,提供了从rtspsrc到appsink的毫秒级优化方案,助力开发者构建零卡顿的智能视觉系统。 阅读详情

相关推荐

Windows 2012 SYSVOL复制失败的处理

题外话:晓原理、知架构、查日志是排错的三件法宝今天在DC1上新建并链接了一个组策略对像,在客户端刷新时,却报下面的错误:“处理组策略失败。Windows无法应用组策略对象LDAP….”如下图所示:于是在客户端用\\domain.com访问,发现\\domain.com\SYSVOL\domain.com\policies下面没有上面报错的组策略对象。这是怎么一回事呢,pin...

weixin_33989780的博客 1675

找到最小的正整数Q,使得Q的各位数的乘积等于N

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_34160277的博客 800

ptrade量化策略之沪深300指数增强

本策略的核心是在沪深300股票池中选股,选择的股票都是市值比较大,业绩比较好的白马股,根据市场相对位置以及基本面因子来选择股票

qq_29301281的博客 1205

输入一个正整数n,返回一个最小正整数m(m至少是2位数),使得m的各位乘积等于n,例如输入36,输出49,输入100,输出455,对于某个n不存在这样的m,请返回-1。

输入一个正整数n,返回一个最小正整数m(m至少是2位数),使得m的各位乘积等于n,例如输入36,输出49,输入100,输出455,对于某个n不存在这样的m,请返回-1。 package hope20141002_01; import java.util.*; public class JingDong { public static void main(String[] args) {

梦想巅峰 5061

股票行情接口,最全的接入方法

股票行情接口一般有两种,一种是WebSocket,一种是http,通过WebSocket可以获取逐笔的股票tick数据,实时并且高效;通过http接口可以获取股票行情接口中的股票历史数据;WebSocket是一种高效的双向通信协议,它允许数据的实时推送,避免了不断的轮询请求。其次,WebSocket允许您订阅特定的数据源或股票数据产品,只接收您感兴趣的信息,提高了数据的效率和可用性。通过接入股票行情数据的HTTP接口,您可以将数据导入到自己的分析工具或系统中,进行更深入的数据分析、模型构建和决策支持。

apifinance的博客 3433

【机器视觉】Halcon 最新版本安装教程(HALCON 24.11.1.1 Progress-Steady)

注:如果使用评估版本,下载前先了解最新评估授权密钥所支持的版本。。近几年不同版本安装过程类似,均可参考本教程。

OpenSeek的博客 3万+

LeetCode 日常填坑

https://leetcode-cn.com/problemset/all/ https://github.com/apachecn/awesome-algorithm/tree/master/docs/Leetcode_Solutions/Python 转载于:https://www.cnblogs.com/iyouyue/p/9771058.html

ac8474的博客 192

复现论文报错解决

博主复现论文代码过程中遇到的各种报错及解决方案~

rellvera的博客 1064

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

赞美月亮的专栏 667

获取抖音中x-secsdk-csrf-token的方法

获取抖音中x-secsdk-csrf-token的方法

sh_moranliunian的博客 2025

【精细解读】xapp585(多通道LVDS接口ADC)

xapp585的参考设计有Verilog和VHDL两种源码。

FPGA艺术家的博客 543

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的博客 1143

STM32入门教程:车牌识别

在本文中,我们介绍了如何使用STM32实现车牌识别功能,并提供了详细的代码案例。通过以上步骤,你可以开始开发自己的车牌识别系统了。希望本文对你有所帮助!

2401_85258012的博客 875

[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

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

深度学习工具包 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")

LeetCode 1. Two Sum 题解

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

cannonjinx的博客 4199

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

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

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

maoersong的专栏 359

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

Leetcode ☞ 1. Two Sum ☆ 【Hashmap】

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

Dr_Unknown的博客 986

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

嗨~ 173

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的博客 268

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

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

TechFlow的博客 231

【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的博客 1028

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 1.Two Sum map 初次使用Markdown*****

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

老夫编代码就是一把梭 1146

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 592
上一篇: 【LeetCode】120. Triangle
下一篇: 【LeetCode】15. 3Sum
coderwait
博客等级 码龄9年 20粉丝 210原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址