当前位置:网站首页>1.两数之和
1.两数之和
2022-07-26 14:37:00 【superkcl2022】


1. 暴力解法
/** * 描述 暴力解法 O(n^2) */
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i = 0; i < nums.length; i++){
for(int j = i+1; j < nums.length; j++){
if(nums[i] + nums[j] == target){
return new int[]{
i,j};
}
}
}
return new int[]{
};
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] ints = solution.twoSum(new int[]{
2, 7, 11, 15}, 9);
System.out.println(ints[0] + " " + ints[1]);
}
}
2. 哈希表
/** * 项目名: leetcode * 包名: com.kcl.L1 * 文件名 Solution * 创建者 * 创建时间: 2022/7/10 10:49 AM * 描述 hash O(n) */
class Solution2 {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<>();
int len = nums.length;
for(int i = 0; i < len; i++){
//往前找
if(map.get(target-nums[i]) != null){
return new int[]{
i,map.get(target-nums[i])};
}else{
map.put(nums[i],i);
}
}
return new int[]{
};
}
public static void main(String[] args) {
Solution2 solution = new Solution2();
int[] ints = solution.twoSum(new int[]{
2, 7, 11, 15}, 9);
System.out.println(ints[0] + " " + ints[1]);
}
}
边栏推荐
- VBA upload pictures
- unity透明通道的小技巧
- Use of delve for go development and debugging
- Kubernetes ---- pod configuration resource quota
- 【方差分析】之matlab求解
- PyTorch中 torch.nn与torch.nn.functional的区别
- Use cpolar to build a commercial website (apply for website security certificate)
- selenium 代码存放
- 31. Opinion-based Relational Pivoting forCross-domain Aspect Term Extraction 阅读笔记
- SiamRPN++:深层网络连体视觉跟踪的演变
猜你喜欢

Win11 running virtual machine crashed? Solution to crash of VMware virtual machine running in win11

llcc68广播唤醒简单说明

RPN:Region Proposal Networks (区域候选网络)

Canvas mesh wave animation JS special effect

【干货】MySQL索引背后的数据结构及算法原理

堆叠降噪自动编码器 Stacked Denoising Auto Encoder(SDAE)

C# Winfrom 常用功能整合
![[1.2. return and risk of investment]](/img/61/0135c429225e1c18705749a20e2a96.png)
[1.2. return and risk of investment]
![[draw with toolbar]](/img/d4/9cb06599f9a8fe5f8149cb7870c103.png)
[draw with toolbar]

Instructions for various interfaces of hand-held vibrating wire collector vh03
随机推荐
【干货】MySQL索引背后的数据结构及算法原理
C# 常用功能整合
Sqldeveloper tools quick start
[Nuxt 3] (十二) 项目目录结构 1
Flask send_ Absolute path traversal caused by file function
Win11 running virtual machine crashed? Solution to crash of VMware virtual machine running in win11
[dry goods] data structure and algorithm principle behind MySQL index
TransC知识表示模型
智能家居行业发展,密切关注边缘计算和小程序容器技术
WPF common function integration
[draw with toolbar]
.net6 encounter with the League of heroes - create a game assistant according to the official LCU API
【常微分方程求解及绘图之求解小船行走轨迹】
median filter
CAS based SSO single point client configuration
Unity学习笔记–无限地图
Siamfc: full convolution twin network for target tracking
SA-Siam:用于实时目标跟踪的孪生网络
[ostep] 02 virtualized CPU - process
[ostep] 03 virtualized CPU - restricted direct execution mechanism