当前位置:网站首页>【刷题记录】1. 两数之和
【刷题记录】1. 两数之和
2022-07-05 20:21:00 【InfoQ】
前言
一、题目描述
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
输入: nums = [3,2,4], target = 6
输出: [1,2]
1 <= s.length <= 1000
s 由英文字母(小写和大写)、',' 和 '.' 组成
1 <= numRows <= 1000
二、思路分析:
1.简单直接暴力解法 - 遍历
class Solution {
public int[] twoSum(int[] nums, int target) {
int length = nums.length;
//保证num[j]存在 i 遍历到 n-2 为止
for (int i = 0; i < length - 1; i++) {
//避免重复,遍历从当前数组后面开始
for (int j = i + 1; j < length; j++) {
if (nums[i] + nums[j] == target) return new int[]{i,j};
}
}
return new int[]{};
}
}

2.改进下解法-哈希表
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[]{};
}
}

总结
边栏推荐
- mongodb文档间关系
- 1:引文;
- [C language] three implementations of quick sorting and optimization details
- 基金网上开户安全吗?去哪里开,可以拿到低佣金?
- 【数字IC验证快速入门】7、验证岗位中必备的数字电路基础知识(含常见面试题)
- c語言oj得pe,ACM入門之OJ~
- Leetcode brush question: binary tree 14 (sum of left leaves)
- 中金财富在网上开户安全吗?
- Document method
- Bzoj 3747 poi2015 kinoman segment tree
猜你喜欢

Go language | 03 array, pointer, slice usage

Wechat applet regular expression extraction link

JS implementation prohibits web page zooming (ctrl+ mouse, +, - zooming effective pro test)

About the priority of Bram IP reset

Rainbow 5.7.1 supports docking with multiple public clouds and clusters for abnormal alarms

【数字IC验证快速入门】3、数字IC设计全流程介绍

基础篇——配置文件解析

- Oui. Net Distributed Transaction and Landing Solution

Oracle-表空间管理

Hong Kong stocks will welcome the "best ten yuan store". Can famous creative products break through through the IPO?
随机推荐
Mysql频繁操作出现锁表问题
CVPR 2022 | 常见3D损坏和数据增强
Introduction to dead letter queue (two consumers, one producer)
CCPC 2021威海 - G. Shinyruo and KFC(组合数,小技巧)
ICTCLAS用的字Lucene4.9捆绑
无卷积骨干网络:金字塔Transformer,提升目标检测/分割等任务精度(附源代码)...
leetcode刷题:二叉树17(从中序与后序遍历序列构造二叉树)
Schema和Model
kubernetes资源对象介绍及常用命令(五)-(ConfigMap&Secret)
Go language | 01 wsl+vscode environment construction pit avoidance Guide
什么是pyc文件
mongodb/文档操作
如何形成规范的接口文档
银河证券在网上开户安全吗?
MySql的root密码忘记该怎么找回
14. Users, groups, and permissions (14)
model方法
leetcode刷题:二叉树13(相同的树)
1: Citation;
基金网上开户安全吗?去哪里开,可以拿到低佣金?