【LeetCode】1. Two Sum 解题报告
2016-05-21 17:14
375 查看
转载请注明出处:/article/11841686.html
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
返回两个下标组成的数组。
该方法时间复杂度较高,O(n²)。
空间复杂度是O(1)。
然后看到该题目的提示标签是【Array】【Hash Table】,就想到使用HashMap来存储下标和值。
注意将 nums[i] 作为key,将下标 i 作为value。
判断map里面是否存在 target-nums[i] 这个key。
bingo~~
Subject
出处:https://leetcode.com/problems/two-sum/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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Explain
该题目给定一个int型数组,和一个target数值。要求找出数组中两个下标对应的数字之和等于target。返回两个下标组成的数组。
Solution
solution 1
最笨的方法就是循环嵌套。public static int[] twoSum(int[] nums, int target) { int[] result = new int[2]; if (nums == null || nums.length == 0) { return result; } for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { result[0] = i; result[1] = j; return result; } } } return result; }
该方法时间复杂度较高,O(n²)。
空间复杂度是O(1)。
solution 2
虽然方法一通过了测试,但是时间复杂度较高。然后看到该题目的提示标签是【Array】【Hash Table】,就想到使用HashMap来存储下标和值。
/** * 使用HashMap存储 <br /> * * @param nums * @param target * @return */ public static int[] twoSum2(int[] nums, int target) { int[] result = new int[2]; HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(target - nums[i])) { if (i > map.get(target - nums[i])) { result[0] = map.get(target - nums[i]); result[1] = i; } else { result[0] = i; result[1] = map.get(target - nums[i]); } } else { map.put(nums[i], i); } } return result; }
注意将 nums[i] 作为key,将下标 i 作为value。
判断map里面是否存在 target-nums[i] 这个key。
bingo~~
相关文章推荐
- 处理 eclipse 导入报错 Invalid project description,问题
- css常用标签及属性
- /bin/sh: 1: /usr/local/arm/arm-2009q3/bin/arm-none-linux-gnueabi-gcc: not found
- (结构型模式)FACADE——外观模式
- 迪米特法则(LOD)——最少知识原则
- 2016 百度之星初赛 Gym Class(优先队列+拓扑排序)
- ROLL A BALL (Unity 3D 入门) 游戏制作指导 - 滚珠游戏介绍
- Invert Binary Tree
- 课程疑问小结
- 树莓派使用虚拟键盘
- (行为型模式)TEMPLATE METHOD——模板方法模式
- 2016.5.21【初中部 NOIP提高组 】模拟赛A 总结
- 栈的压入、弹出序列——22
- 伟大的数学家马尔可夫,以及他对互联网的重要贡献
- poj2785题解
- SAX - Hello World
- ViewHolder重用机制 RecyclerView+CardView 优化
- Spring-bean作用域scope详解
- (创建型模式)PROTOTYPE——原型模式
- hdu_5695_Gym Class(拓扑排序)