当前位置:网站首页>[record of question brushing] 1 Sum of two numbers
[record of question brushing] 1 Sum of two numbers
2022-07-05 20:25:00 【InfoQ】
Preface
One 、 Title Description
Input :nums = [2,7,11,15], target = 9
Output :[0,1]
explain : because nums[0] + nums[1] == 9 , return [0, 1] .
Input : nums = [3,2,4], target = 6
Output : [1,2]
1 <= s.length <= 1000
s
By the English letters ( Lowercase and upper case )、','
and '.'
form
1 <= numRows <= 1000
Two 、 Thought analysis :
1. Simple direct violent solution - Traverse
class Solution {
public int[] twoSum(int[] nums, int target) {
int length = nums.length;
// Guarantee num[j] There is i Traversing n-2 until
for (int i = 0; i < length - 1; i++) {
// Avoid repetition , The traversal starts after the current array
for (int j = i + 1; j < length; j++) {
if (nums[i] + nums[j] == target) return new int[]{i,j};
}
}
return new int[]{};
}
}
2. Improve the solution - Hashtable
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) return new int[]{map.get(target - nums[i]), i};
map.put(nums[i], i);
}
return new int[]{};
}
}
summary
边栏推荐
猜你喜欢
CTF逆向基础
港股将迎“最牛十元店“,名创优品能借IPO突围?
14、Transformer--VIT TNT BETR
Rainbond 5.7.1 支持对接多家公有云和集群异常报警
【数字IC验证快速入门】6、Questasim 快速上手使用(以全加器设计与验证为例)
Leetcode skimming: binary tree 17 (construct binary tree from middle order and post order traversal sequence)
Wechat applet regular expression extraction link
A way to calculate LNX
ROS2专题【01】:win10上安装ROS2
【数字IC验证快速入门】8、数字IC中的典型电路及其对应的Verilog描述方法
随机推荐
鸿蒙系统控制LED的实现方法之经典
Practical demonstration: how can the production research team efficiently build the requirements workflow?
信息学奥赛一本通 1337:【例3-2】单词查找树 | 洛谷 P5755 [NOI2000] 单词查找树
nprogress插件 进度条
A way to calculate LNX
信息学奥赛一本通 1338:【例3-3】医院设置 | 洛谷 P1364 医院设置
强化学习-学习笔记4 | Actor-Critic
【c语言】快速排序的三种实现以及优化细节
Ffplay document [easy to understand]
1、强化学习基础知识点
Mongodb/ document operation
小程序项目结构
Informatics Orsay all in one 1339: [example 3-4] find the post order traversal | Valley p1827 [usaco3.4] American Heritage
处理文件和目录名
C langue OJ obtenir PE, ACM démarrer OJ
基础篇——配置文件解析
Some problems encountered in cocos2d-x project summary
model方法
[quick start of Digital IC Verification] 7. Basic knowledge of digital circuits necessary for verification positions (including common interview questions)
Leetcode (347) - top k high frequency elements