给定一个整数数组 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]
提示:
枚举数组中的每一个元素x,寻找是否存在一个元素满足target-x。
- class Solution {
- public int[] twoSum(int[] nums, int target) {
- int length = nums.length;
- for(int i=0;i
1;i++){ - int x = target-nums[i];
- for(int j = i+1;j
- if(nums[j]==x){
- return new int[]{i,j};
- }
- }
- }
- return new int[0];
- }
- }
方法二:哈希表
仍然枚举每一个元素x,判断哈希表中是否有元素满足target-x,如果没有满足该条件的,那么就将x放入哈希表中,等待target-y
- class Solution {
- public int[] twoSum(int[] nums, int target) {
- Map
hashtable = new HashMap(); - for(int i =0;i
- int y = target-nums[i];
- if(hashtable.containsKey(y)){
- return new int[]{hashtable.get(y),i};
- }
- hashtable.put(nums[i],i);
- }
- return new int[0];
- }
- }
-
相关阅读:
亚马逊买家号白号批量注册怎么做?
【1day】用友移动管理系统任意文件上传漏洞学习
Elasticsearch 保姆级入门篇
修改ubuntu终端目录背景颜色
0030__Keil MDK 中的 Code、RO-data、RW-dat、ZI-data 分别代表什么意思
智能网卡(SmartNIC):增强网络性能
访问网站提示:您未被授权查看该页恢复办法
数学建模之遗传算法
Hadoop伪分布模式安装
没想到还有这种骚操作~如何使用Golang实现无头浏览器截图?
-
原文地址:https://blog.csdn.net/zmbwcx/article/details/134250530