1. Two Sum
来源:互联网 发布:淘宝返利网都有哪些 编辑:程序博客网 时间:2024/06/03 18:24
1. Two Sum (easy)
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].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
(1)解题思路 o(n2)
使用遍历的方式,取数组中的每一个元素,遍历其后的元素与其相加是否等于目标值。
public class Solution { public int[] twoSum(int[] nums, int target) { int index[] = new int[2]; int i=0, j=0; for (i = 0; i < nums.length; i++) { for (j = i+1; j < nums.length; j++) { if(target == nums[i]+nums[j]){ index[0] = i; index[1] = j; return index; } } } return null; }}
(2)解题思路o(n) 参考的
使用hashmap将值与索引一一映射,同时考虑到了当数组中有重复元素时的情况
eg: nums[] = {0,3,5,0} target = 0
此时键值不是一一对应的,如果key不唯一,而hash(key)是单值函数,就会使得后面添加进来的value覆盖前面的key对应的value,这道题在循环时i是从0开始的,所以这里不会影响结果
代码精炼,时间复杂度低,值得学习
public class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> m = new HashMap<Integer, Integer>(); for(int i = 0; i<nums.length;i++){ m.put(nums[i], i); } for(int i=0; i<nums.length; i++){ if(m.containsKey(target-nums[i]) && m.get(target-nums[i])!=i) return new int[]{i, m.get(target-nums[i])}; } return new int[]{0}; }}
(3)参照上面,可以使用ArrayList实现o(n)
在使用这种方式时,由于数组中有重复元素,所以返回结果时应该要对数组进行重新的排序
ArrayList <Integer> list = new ArrayList<>(); for (int i = 0; i < nums.length; i++) { list.add(nums[i]); } for (int i = 0; i < list.size(); i++) { if(list.contains(target-list.get(i)) && list.indexOf(target-list.get(i))!=i){ int index[]=new int[]{i,list.indexOf(target-list.get(i))}; Arrays.sort(index); return index; } } return new int[]{0};
0 0
- 1. Two Sum && 167. Two Sum II
- LeetCode 1. Two Sum
- [LeetCode]1.Two Sum
- LeetCode 1.Two Sum
- LeetCode --- 1. Two Sum
- 1.Two Sum
- [Leetcode] 1. Two Sum
- leetcode---1.Two sum
- 1.Two Sum
- [Leetcode] 1. Two Sum
- LeetCode 1.Two Sum
- 1. Two Sum
- 1. Two Sum
- 1. Two Sum Ruby
- LeetCode 1.Two Sum
- LeetCode 1.Two Sum
- 1. Two Sum
- 1.Two Sum
- VS2010调试极慢,因为启动了IntelliTrace
- 微信小程序开发思路
- ajax配合struts2(ssh2)实现无刷新验证用户名是否唯一
- android The method of type must override a superclass method
- 分析android程序项目结构
- 1. Two Sum
- 快速排序法-java实现
- 提高你开发效率的十五个Visual Studio 2010使用技巧
- DVWA漏洞学习(1)环境搭建
- Visual Studio 2012 编译错误【error C4996: 'scanf': This function or variable may be unsafe. 】的解决方案
- android学习目录
- ASP.NET中的inherits、CodeFile、CodeBehind的区别详解
- 递归画图形
- 正则表达式