当前位置:网站首页>1. 两数之和(LeetCode题目)
1. 两数之和(LeetCode题目)
2022-06-26 09:36:00 【later_rql】
题目描述
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
解题思路
思路一:暴力求解。
依次判断数组中每两个元素之和与target的大小关系,即可得到相等的两个元素的下标,并返回。
时间复杂度:O(N^2)
空间复杂度:O(l)
思路二:哈希表。
利用哈希表的特殊性来进行判断,查找hash表中有无与target-nums[i]相等的元素,每次就将数据添加入hash表中。
时间复杂度:O(n)
空间复杂度:O(n)
注:对于每一个 x,我们首先查询哈希表中是否存在 target - x,然后将 x 插入到哈希表中,即可保证不会让 x 和自己匹配。
代码
解法一:暴力求解
public static int[] twoSum(int[] nums, int target) {
int[] arr=new int[2];
for(int i=0;i<nums.length-1;i++){
for(int j=i+1;j<nums.length;j++){
if((nums[i]+nums[j])== target){
arr[0]=i;
arr[1]=j;
}
}
}
return arr;
}
解法二:哈希表。
public static int[] twoSum_hash(int[] nums, int target){
Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; ++i) {
if (hashtable.containsKey(target - nums[i])) {
return new int[]{
hashtable.get(target - nums[i]), i};
}
hashtable.put(nums[i], i);
}
return new int[0];
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
边栏推荐
- Poj3682 king arthur's birthday celebration (probability)
- SQL query duplicate record
- c语言语法基础之——函数定义学习
- 调用api接口生成不同颜色的微信小程序二维码
- thinkphp6.0的第三方扩展包,支持上传阿里云,七牛云
- Force buckle ----- remove the maximum and minimum values from the array
- DAY 3 数组,前置后置,字符空间,关键词和地址指针
- Leetcode connected to rainwater series 42 (one dimension) 407 (2D)
- 力扣------从数组中移除最大值和最小值
- Code statistics tools cloc and SCC
猜你喜欢

自动化测试——pytest本身及第三方模块介绍及使用

install opencv-contrib-dev to use aruco code

我的创作纪念日

WGCLOUD的web ssh服务端口是多少
![Logical English structure [key points]](/img/4b/52a666ed01087adbc5fa4f9e1db393.png)
Logical English structure [key points]

如何更改微信小程序二维码物料颜色

Druid data source for background monitoring

Some problems to be considered when designing technical implementation scheme
![[trajectory planning] testing of ruckig Library](/img/c7/51c0f6dc3bf7c7fa4528118a4c32fa.png)
[trajectory planning] testing of ruckig Library

定制拦截器
随机推荐
c语言语法基础之——局部变量及存储类别、全局变量及存储类别、宏定义 学习
自动化测试——关于unitest与pytest初始化共存问题
Redis master-slave replication in win10 system
Getting started with Flink - word statistics
c语言语法基础之——函数嵌套、递归 小程序斐波那契之和、阶乘
c语言语法基础之——指针( 多维数组、函数、总结 ) 学习
2021-11-29 quintic polynomial of trajectory planning
國際化配置
教你用shell脚本检测服务器程序是否在运行
Summary of common commands of vim
Some problems to be considered when designing technical implementation scheme
Automated testing -- Introduction and use of pytest itself and third-party modules
Recyclerview implements flow layout (LinearLayout with line wrap) (flexboxlayoutmanager)
install ompl. sh
Automated testing -- Introduction and example of pytest framework
#云原生征文# 在 Google Kubernetes Cluster 上使用 HANA Expression Database Service
Day 3 array, pre post, character space, keyword and address pointer
Speed test of adding, deleting, modifying and querying 5million pieces of data in a single MySQL table
libmagic 介绍
LeetCode 剑指 Offer II 091.粉刷房子 - 原地修改