【LeetCode】Two Sum 解题报告
来源:互联网 发布:决战武林雨扇进阶数据 编辑:程序博客网 时间:2024/05/16 03:50
【LeetCode】Two Sum 解题报告
标签(空格分隔): LeetCode
题目地址:https://leetcode.com/problems/two-sum/#/description
题目描述:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
Ways
这个题首先想到的是时间复杂度O(n^2)的遍历,但是肯顶会超时,所以想到用HashMap保存已经有的数据出现的额位置,这样可以使如果要求的数字出现的时候不再继续遍历,及时停止即可。有个技巧就是判断差是否在HashMap中,而不是遍历一遍HashMap来求和。
public class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i = 0; i < nums.length; i++){ if(map.containsKey(target - nums[i])){ return new int[]{map.get(target - nums[i]), i}; }else{ map.put(nums[i], i); } } return new int[2]; }}
Date
2017 年 5 月 18 日
阅读全文
0 0
- LeetCode 解题报告 Two Sum
- LeetCode-Two Sum-解题报告
- [LeetCode] Two Sum 解题报告
- 【LeetCode】Two Sum 解题报告
- [Leetcode]之一《two sum》解题报告
- Leetcode (1) Two Sum 解题报告
- [leetcode] 1. Two Sum 解题报告
- LeetCode 1. Two Sum 解题报告
- LeetCode 1.Two Sum 解题报告
- 【LeetCode】1. Two Sum 解题报告
- LeetCode 167.Two Sum II 解题报告
- LeetCode 1.Two Sum 解题报告
- [Leetcode] 1. Two Sum 解题报告
- leetcode解题报告1. Two Sum
- leetcode | 1. Two sum 解题报告
- [LeetCode 解题报告]001.Two Sum
- 【LeetCode】1.Two Sum解题报告
- LeetCode(1) Two Sum解题报告
- Eclipse安装Kotlin插件后新建项目时不显示新建Kotlin项目
- ScrollView 中EditText 内容滑动显示
- Maven学习总结(9)——使用Nexus搭建Maven私服
- 子网掩码与子网数目之间的换算
- python使用codecs模块进行文件操作-读写中英文字符
- 【LeetCode】Two Sum 解题报告
- 通讯录
- python导入xlwt库 xlrd库
- 利用51单片机输出pwm
- mac adb 连接不到genymotion 虚拟机的问题
- 大数据浪潮下,前端工程师眼中的完整数据链图
- 1.4 单文档MFC应用程序实例
- 让Mysql替你完成时间戳和时间格式的转换
- 【转载】Py 编码的真相