LeetCode 1: Two Sum
来源:互联网 发布:acid3 知乎 编辑:程序博客网 时间:2024/06/12 20:11
题目:
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].题目分析:
给定一个整形的数组,返回数组中两个元素的下标,这两个数的和为给定的值。假设对于每个确定的输入值都只有一种解。
思路:
这个题在LeetCode OJ上给出了三种解决方案:Brute force(简单匹配算法)、Two-pass hash table、 One-pass hash table。后两种笔者不知道怎么翻译了……有时候翻译成中文倒是没有英文那么直观。
对于第一种Brute force,网上有说成是暴力算法的,主要就是遍历,时间复杂度高是O(n^2),空间复杂度是O(1)直接上代码:
public class Solution { public int[] twoSum(int[] nums, int target) { int result[] = new int[2]; int i; int j; for(i=0;i<nums.length-1;i++) { for(j=i+1;j<nums.length;j++) if (nums[i] + nums[j] == target) { result[0] = i; result[1] = j; return result; } } return null; }}
Two-pass hash table:最主要的思路来源一个问题“对于一个数组来说,维护其字面值和索引的最好的方式是什么?是哈希表。”首先将所有元素存储到哈希表中,遍历nums中的元素,每遍历一个元素时使用target-遍历元素,得到的结果再去哈希表中找,寻找的时间复杂度接近O(1),这样,我们只需要遍历一遍就能找到结果。整个算法的时间复杂度是O(n),空间复杂度是O(n)。算法的核心就是时空转换嘛,上代码:
public class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for(int i=0;i<nums.length;i++) { map.put(nums[i],i); } for(int i=0;i<nums.length-1;i++) { int complement = target - nums[i]; if(map.containsKey(complement)&&map.get(complement)!=i) { return new int[] {i,map.get(complement)}; } } return null; }}
One-pass hash table:我个人觉得这个算法棒极了,和第二种算法的区别在于思路!思路!思路!重要的事情说三遍!在建立哈希表的同时就可以一边看当前哈希表中是否有符合条件的值,如果有,哈希表还没建完就找到了答案,岂不妙哉?虽然时间复杂度和空间复杂度同第二种算法~,话不多说上代码:
public class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for(int i=0;i<nums.length;i++) { int complement = target - nums[i]; if(map.containsKey(complement)&&map.get(complement)!=i) { return new int[] {i,map.get(complement)}; } map.put(nums[i],i); } return null; }}
0 0
- LeetCode 1 - Two Sum
- leetcode 1 Two Sum
- Leetcode【1】:Two Sum
- [leetcode 1] Two Sum
- 【leetcode-1】Two Sum
- [leetcode 1] Two Sum
- [Leetcode] 1 - Two Sum
- LeetCode (1) Two Sum
- LeetCode 1:《Two Sum》
- LeetCode | #1 Two Sum
- leetcode-1 Two Sum
- Two Sum | LeetCode(1)
- [Leetcode]1Two Sum
- leetcode 1 Two Sum
- leetcode #1 Two Sum
- leetcode 1:Two Sum
- LeetCode 1 Two Sum
- leetcode #1 two sum
- mave的依赖范围
- android 高仿36氪注册登录时输入输出框的动画效果
- 自己摸索的锐捷Linux客户端使用方法(基于ubuntu13.04)
- 【三层架构】登陆实例
- UMeditor图片上传失败之jsp与.NET版本(转载+原创)
- LeetCode 1: Two Sum
- 根据域名查找IP地址
- easyui datagrid 点击表头排序问题
- 怎么用几何画板坐标绘制点
- Android 上传文件到服务器实例详解
- 使用百度网盘+Git,把版本控制托管到云端
- 自己写的两布局界面
- String,StringBuilder和StringBuffer_思维导图总结
- 明细表删除序号及name属性索引未刷新