当前位置:网站首页>力扣习题集1--两数之和
力扣习题集1--两数之和
2022-04-22 23:58:00 【嘉祐-小萝卜算子】
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9 输出:[0,1] 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:
输入:nums = [3,2,4], target = 6 输出:[1,2]
示例 3:
输入:nums = [3,3], target = 6 输出:[0,1]
提示:
2 <= nums.length <= 104-109 <= nums[i] <= 109-109 <= target <= 109- 只会存在一个有效答案
进阶:你可以想出一个时间复杂度小于 O(n2) 的算法吗?
我的实现
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result=new int[2];
Map<Integer,Integer> map=new HashMap();
//题目中已知nums的length>2,不必讨论 是否为空,存在越界的问题
//因为是有两个数组成,所以 可以先把index=0的先放到map里面,减少一层for循环
map.put(target-nums[0],0);
for(int i=1;i<nums.length;i++){
if(map.containsKey(nums[i])){
result[0]=map.get(nums[i]);
result[1]=i;
break;
}else{
map.put(target-nums[i],i);
}
}
return result;
}
}
版权声明
本文为[嘉祐-小萝卜算子]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_39282730/article/details/124350987
边栏推荐
- Complete set of JUC (1)
- Introduction to opencv (II) -- affine transformation and perspective transformation
- 2022-4-22 job MySQL single table query
- [transaction management]
- unbuntu18. 04 installing gamit10 71 problem solution
- Gets the range of the currently selected string
- Vs write assembly
- xpath定位
- LeetCode 1446 - 1449
- Select all text
猜你喜欢

Thought of reducing Governance -- detailed summary of binary search

Conjugate gradients (4)
![[turtle confession collection]](/img/97/6f1008386931bcb93655d94121e2c4.png)
[turtle confession collection] "the moon at the bottom of the sea is the moon in the sky, and the person in front of us is the sweetheart." More joy and peace for the rest of your life ~ (with 3 sourc

unbuntu18. 04 installing gamit10 71 problem solution

Fundamentals of programming language (1)

浅谈LD_PRELOAD劫持

No module named 'Django is reported when Django specifies the database_ test. settings‘

OpenCv入门(二)——仿射变换和透视变换

“亿”点点技术情怀

重新安装window10
随机推荐
Character set (de duplication)
FPGA(四)数字IC面试的四个基本问题
FPGA (V) one of RTL codes (cross clock domain design)
【事務管理】
获取某一点的颜色
Typora样式调优
(mm-2018) local convolutional neural network for pedestrian re recognition
Beijing University of Aeronautics and Astronautics launched the trial of cnopendata
学习 Rust
FileNotFoundError: [Errno 2] No such file or directory: 'image/1. Jpg 'problem solving
Redis的基本使用
Complete set of JUC (1)
Merge two ordered arrays
Install the most complete version of ActiveMQ under the official website in 2022 and the official website access method
Notes on "Introduction to dynamic programming" (under update)
Interviewer: how big is the performance difference between ArrayList and LinkedList?
Visual studio 2019 restore default settings
English pronunciation and notes commonly used in OC
matlab-day01
Bonner ultrasonic sensor t30uxda