当前位置:网站首页>力扣-两数之和
力扣-两数之和
2022-07-01 03:02: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]
二、解法1
public int[] twoSum1(int[] nums, int target) {
int[] indexs = new int[2];
// 双重循环 循环极限为(n^2-n)/2
for (int i = 0; i < nums.length; i++) {
for (int j = nums.length - 1; j > i; j--) {
if (nums[i] + nums[j] == target) {
indexs[0] = i;
indexs[1] = j;
System.out.println(Arrays.toString(indexs));
return indexs;
}
}
}
return indexs;
}三、解法2
public int[] twoSum3(int[] nums, int target) {
int[] indexs = new int[2];
// 建立k-v ,一一对应的哈希表
HashMap<Integer, Integer> hash = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
if (hash.containsKey(nums[i])) {
indexs[0] = i;
indexs[1] = hash.get(nums[i]);
System.out.println(Arrays.toString(indexs));
return indexs;
}
// 将数据存入 key为补数 ,value为下标
hash.put(target - nums[i], i);
}
return indexs;
}边栏推荐
- Multithreaded printing
- Densenet network paper learning notes
- Chapitre 03 Bar _ Gestion des utilisateurs et des droits
- 如何校验两个文件内容是否相同
- In the industrial Internet, "small" programs have "big" effects
- Introduction and basic knowledge of machine learning
- Sampling Area Lights
- Codeforces Round #416 (Div. 2) C. Vladik and Memorable Trip
- 第03章_用户与权限管理
- 最好用的信任关系自动化脚本(shell)
猜你喜欢

The best learning method in the world: Feynman learning method

Example of Huawei operator level router configuration | example of configuring optionc mode cross domain LDP VPLS
性能测试常见面试题

Metadata in NFT

Chapitre 03 Bar _ Gestion des utilisateurs et des droits

如何校验两个文件内容是否相同

Lenovo x86 server restart management controller (xclarity controller) or TSM method

So easy 将程序部署到服务器

Xception learning notes

HTB-Lame
随机推荐
The 'mental (tiring) process' of building kubernetes/kubesphere environment with kubekey
PTA 1016
【小程序项目开发 -- 京东商城】uni-app 商品分类页面(上)
Poj-3486-computers[dynamic planning]
Restcloud ETL WebService data synchronization to local
Druid monitoring statistics source
XXL job User Guide
C#实现图的深度优先遍历--非递归代码
Voici le programme de formation des talents de SHARE Creators!
servlet【初识】
Design practice of current limiting components
Communication protocol -- Classification and characteristics Introduction
Is it safe to open an account online in a small securities firm? Will my money be unsafe?
Contrastive learning of Class-agnostic Activation Map for Weakly Supervised Object Localization and
LeetCode_ Stack_ Difficulties_ 227. basic calculator (excluding multiplication and division)
[linear DP] longest common subsequence
[applet project development -- JD mall] uni app commodity classification page (first)
Mouse over effect 10
Redis分布式锁的8大坑
咱就是说 随便整几千个表情包为我所用一下