Two Sum 数组中找两个之和为sum@LeetCode

电面:给一个数组找出和为k的两个数 如标题所述,其实LeetCode上也有道差不多的题,Two Sum返回这两个数的对应下标。 那我就按LeetCode上那道题来写吧。 先用双指针的方法嘛,不过LeetCode上面是要求返回下标,那么就不能用sort直接对原本的数组进行排序,会影响之前本来的下标。所以得先复制一个数组出来。 双指针没什么好说的,因为已经排好序了,一个从最左端走,一个从最右端走。写这个主要是为学习一下C中的qsor 阅读详情

思路:

用Hashtable,遍历数组时对每个数边放边查找

package Level2;

import java.util.HashMap;
import java.util.Hashtable;

/**
 * Two Sum
 * 
 * Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
 */
public class S1 {

	public static void main(String[] args) {
		Hashtable<Integer, Integer> ht = new Hashtable<Integer, Integer>();
		System.out.println(ht.get(22));
	}

	public int[] twoSum(int[] numbers, int target) {
		// 放值和数组下标
		Hashtable<Integer, Integer> ht = new Hashtable<Integer, Integer>();
		int[] ret = new int[2];
		
		for(int i=0; i<numbers.length; i++){
			// 对每一个数边放边查找
			if(ht.get(target-numbers[i]) != null){
				ret[0] = ht.get(target-numbers[i]) + 1;
				ret[1] = i+1;
			}else{
				ht.put(numbers[i], i);
			}
		}
		
		return ret;
	}
}




import java.util.*;
public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        Hashtable<Integer, Integer> ht = new Hashtable<Integer, Integer>();
        int[] ret = {0,0};
        for(int i=0; i<numbers.length; i++) {
            Integer index = ht.get(target-numbers[i]);
            if(index != null) {
                ret[0] = index+1;
                ret[1] = i+1;
            }
            ht.put(numbers[i], i);
        }
        return ret;
    }
}




数组中寻找和为sum的两个元素 给定一个无序数列,和一个整数sum,求数组中的两个数a和b,使得a+b=sum。 解法:先升序排序O(n logn),再用两个游标ind1,ind2从两边开始向中间靠拢, 如果an[ind1]+an[ind2]>sum,则ind2--,否则ind1++,知道找到sum为止。最后,如果ind1==ind2,说明没找到,返回-1。 时间复杂度O(nlogn),空间复杂度O(1) #includ 阅读详情

相关推荐

别再手动填序号了!用Python脚本在Arcgis属性表里实现分组自动编号(附完整代码)

本文详细介绍了如何利用Python脚本在Arcgis属性表中实现分组自动编号,告别低效的手工操作。通过核心代码解析和实战教程,帮助GIS工程师快速掌握自动化编号技术,提升工作效率并降低错误率。特别适合城市规划、国土调查等需要处理大量分组数据的场景。

weixin_42532473的博客 307

在一个数组中找出两个数,这两个数之和为指定目标值,返回这两个数下标(leecode)(c++)

本文主要总结在一个数组中取出两个数,这两个数满足条件为:两数之和为制定目标值target,并且函数返回这两个数下表。 示例: 给定 nums = [5,6,7,8,9,10], target = 19 因为 nums[4] + nums[5] = 9 + 10 = 19 所以返回 [4, 5] 1.1解题思路 根据题意,可以看出这是一个组合问题,也就是高中数学常见的排列组合基本问题。 ...

净无邪博客 6433

保姆级教程:用Python仿真OFDM系统(附抗多径干扰优化方案)

本文提供了一份详细的Python仿真OFDM通信系统教程。通过NumPy和Matplotlib,从二进制比特流开始,逐步构建完整的OFDM系统模型,涵盖IFFT、循环前缀等核心概念。重点探讨了如何对抗多径干扰,并提供了优化方案,通过误码率曲线直观对比性能,适合通信工程学习和物理层开发实践。

weixin_29230649的博客 231

一个无序数组中两个数之和等于给定的值sum

【问题描述】 给定一个数组,求两个数之和=给定值sum的所有组合个数。 【变形】两个数之和=sum的任意一组数 【方法一】穷举法 从数组中任意找两个数,看其和是否=sum。时间复杂度O(N^2) 【方法二】先排序,然后定义两个指针,一个i=0指向数组头,一个j=len-1指向数组的尾,看其和是否==sum;若==,则查找成功返回;若>sum,则尾指针j--;若 时间复杂

suibianshen2012的专栏 1万+

搜索神器Perplexity的详细使用方法(持续更新)

本文主要介绍了ChatGPT的互补工具Perplexity的详细使用方法,希望对新手有所帮助。需要说明的是,Perplexity不需要上网工具,很方便新手和小白上手使用。Perplexity的官网链接为:https://www.perplexity.ai/ 。 文章目录 1. 为什么要讲Perplexity? 2. 详细使用方法 2.1 使用要点一 2.2 使用要点二 2.3 使用要点三

herosunly的博客 8万+

Python爬虫实战:股票历史数据抓取与量化回测全流程详解

我们以**东方财富网(eastmoney.com)和雪球网(xueqiu.com)**为主要目标,演示如何爬取A股历史行情。最常用的HTTP请求库,简单易用,适合静态页面数据请求。本文详细介绍了从股票历史数据抓取到简单回测的完整流程,代码示例基于最新技术,结构清晰,适合初学者和进阶者学习量化投资实战。希望对你入门Python爬虫和量化交易有所帮助!

2201_76125261的博客 1778

求解数组中任意两个元素的和最接近某一个数

题意是这样的:求解一个数组中元素a和b,其和sum=a+b,sum最接近num的数两个。array是一个整型数组。 其求解方式如下: //求解数组中元素a和b,其和sum=a+b,sum最接近num的数两个。 //求解思想是:对数组进行顺序排序,然后对数组中的每个数遍历每个数能求得一个最优值,然后对每对值大小sum与给出的这个数num做比较,找出绝对值相差最小的那个数。 //以下程序是对以上的

shyk的博客 4746

罗克韦尔AB PLC_FactoryTalk无法登录的解决方法

罗克韦尔AB PLC_FactoryTalk无法登录的解决方法

Robot_PLC_HMI_Automation 3574

HashTable-1-Two Sum

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

fighting! 457

OpenRubrics:自动化评估工具优化LLM对齐效果

在大型语言模型(LLM)应用中,模型输出与人类价值观的对齐是关键挑战。传统人工反馈强化学习(RLHF)依赖大量标注,成本高且一致性差。OpenRubrics作为开源工具,通过结构化准则实现自动化评估,显著提升效率。其核心原理是将主观评价转化为可量化的多维指标,支持动态权重调整,并兼容主流RLHF框架。该工具在降低标注成本的同时,通过Fleiss' Kappa系数等指标保证评估一致性,适用于多语言和医疗等专业领域,为LLM对齐提供了工程化解决方案。

weixin_28730037的博客 357

SAPGUI excel 导出时遇到的运行时错误:STRING_SIZE_TOO_LARGE

当报表导出需求远超单一 XLSX 文件的物理承载力时,与其在 SAPGUI 中硬拼 2 GB 限制,不如把分页、过滤、流式写入作为设计前提。掌握 ABAP2XLSX 或 CSV + Power Query 等工具链,既能满足审计合规,又能让应用服务器远离的噩梦。祝你在下一次导出海量数据时,既高效又优雅。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 638

常见面试算法题:给定数组中寻找加和为特定数的两个数

问题描述: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 sam

studyless的博客 1523

Spring AI 项目实战(五):Spring Boot + AI + DeepSeek + Redis 实现聊天应用上下文记忆功能(附完整源码)

本文介绍了如何基于Spring Boot 3.2、Spring AI 1.0.0-M4、DeepSeek API和Redis构建具备上下文记忆功能的智能聊天应用。项目采用现代化技术栈,包括Java 17、Maven、Lombok等,实现了智能对话、会话管理、异常处理等核心功能。文章详细讲解了环境搭建、配置管理(含Redis和AI服务集成)、核心组件设计(如消息实体、控制器和服务层实现),以及完整的项目结构。该项目提供了美观的Web界面和REST API,支持对话上下文存储(通过Redis实现)和系统监控,可

博客 828

leetcode 1.两数之和(two sum)

题目描述:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。 解答:暴力法费时费力,利用字典结构,以空间换时间,时间复杂度为O(n),空间复杂度为O(n) class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: d = {}

一只坚持的码农 226

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

算法练习1.Two Sum 数组两个和为目标值的下标(map)

Two Sum 给定一个目标整数target,找出数组中和为target的两个数的下标 C++: class Solution { public:    vector twoSum(vector& nums, int target) {        vector solve;        for(int i = 0 ; i        {            for(i

Howie的博客 704

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

LeetCode-Easy部分标签为HashTable 1. Two Sum(一种战胜95%的提交版本的算法)

给定一个整数数组,如果两个数相加等于目标值,则返回它们的索引。假定,只有一组解,同一个元素不能用两次。给出了两种解决方法和一种假定数组为有序的解决方法。

相信相信的力量 1409

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

Valid Number 判断一个string是不是有效地数字表达式 @LeetCode

这道题看了看网上的解法,很多都做得很麻烦。其实我觉得,这道题就是考察正则表达式。 package Level2; /** * Valid Number * * Validate if a given string is numeric. Some examples: "0" => true " 0.1 " => true "abc" => false "1 a" =>

1万+

Maximum Subarray 最大子数组和(连续)@LeetCode

package Level3; import java.util.Arrays; /** * * Maximum Subarray * * Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, give

6667

Binary Tree Level Order Traversal II 二叉树按层遍历(反向输出)@LeetCode

树的Level Order Traversal加上ArrayList翻转 package Level3; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import Utility.TreeNode; /** * Binary Tree Level Order T

5192

Binary Tree Level Order Traversal 分层遍历二叉树@LeetCode

package Level3; /** * Binary Tree Level Order Traversal * * Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example: G

5153

Merge Intervals 合并区间@LeetCode

采用的是和Insert Interval一样的思想,只不过最开头要先排序一下,用到了java的Collections.sort(List list, Comparator c) 自己实现了一个Comparator的compare方法 package Level4; import java.util.ArrayList; import java.util.Collections; im

5082

Evaluate Reverse Polish Notation 求RPN的值@LeetCode

用一个Stack就很容易做到了,这道题的最大发现是:这道题是2013-11-27发布出来的,到今天,短短半个月内,居然提交量快到了1万!!! 居然有这么多人都在刷题!!压力山大! package Level3; import java.util.Stack; /** * * Evaluate Reverse Polish Notation * * Evaluate t

4522

Text Justification 文本对齐 @LeetCode

快被这道题搞死了。。 根据这篇重写了 http://www.cnblogs.com/TenosDoIt/p/3475275.html 分析:这一题需要注意两个点,a、当该行只放一个单词时,空格全部在右边 b、最后一行中单词间只有一个空格,其余空格全部在右边。然后只要贪心选择,在一行中尽量放多的单词。 package Level4; import java.util.ArrayL

4510

Celebrity Problem

Celebrity Problem import java.util.Stack; /** In a party of N people, only one person is known to everyone. Such a person may be present in the party, if yes, (s)he doesn’t know anyone in t

3820

3Sum 数组找3数之和为0 @LeetCode

排序,二分法查找,前后双指针 package Level3; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * 3Sum * Given an array S of n integers, are there el

3538
上一篇: Reverse Integer 翻转数字@LeetCode
下一篇: 软件工程师薪酬最高的25家公司!!!
chiiis
博客等级 码龄14年 422粉丝 429原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值