【LeetCode】Two Sum 题解报告
来源:互联网 发布:画电气图软件 编辑:程序博客网 时间:2024/06/02 03:52
[题目]
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.
For Example: Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
[解析]
这是一道简单题,题目很好理解,就是在一个数组中找到两个数的和等于所要求的值,于是最直接想法,两重循环求得结果。
- 解法1:
public static int[] twoSum(int[] nums, int target){ if(nums == null || nums.length < 2) return null; int[] res = new int[2]; boolean flag = true; for(int i=0;i<nums.length&&flag;i++){ int tmp = target - nums[i]; for(int j=i+1;j<nums.length;j++){ if(nums[j] == tmp){ res[0] = i; res[1] = j; flag = false; break; } } } if(flag) return null; else return res;}
上面的时间效率是O(n^2).很明显,算法还可以更优。
- 解法2:
将数组中的元素存放到一个HashMap中,数组的值作为key,数组的下标作为value。利用HashMap的O(1)的查找效率可以得到更高效率的解法,总的时间效率为O(n).
public static int[] twoSum1(int[] nums, int target){ if(nums == null || nums.length < 2) return null; HashMap<Integer, Integer> hashNum = new HashMap<Integer, Integer>(); for(int i=0;i<nums.length;i++){ Integer n = hashNum.get(nums[i]); if(n == null)hashNum.put(nums[i], i); n = hashNum.get(target - nums[i]); if(n != null && n<i){ return new int[]{n,i}; } } return null;}
这里需要注意的是,由于HashMap中的元素不能重复,所以相同元素仅存一次。这里做了处理,即仅存放重复元素第一次出现的那个元素。如果target的值刚好是两个重复元素的和,也不会受到影响。
例如,nums = {3,4,3,5},target = 6,输出的结果是[0,2].
0 0
- 【LeetCode】Two Sum 题解报告
- LeetCode题解:Two Sum
- LeetCode题解:Two Sum
- leetcode-Two Sum[题解]
- [LeetCode题解001]Two Sum
- LeetCode题解 || Two Sum问题
- LeetCode 1 Two Sum 题解
- [Leetcode题解]001 Two Sum
- 1. Two Sum : LeetCode 题解
- leetcode题解-1.Two Sum
- [LeetCode] Two Sum Python 题解
- leetcode 题解 1. Two Sum
- LeetCode 1 Two Sum题解
- LeetCode题解(1)--Two Sum
- LeetCode题解-1-Two Sum
- LeetCode题解 C++ Two Sum
- leetcode题解-1. Two Sum
- LeetCode 解题报告 Two Sum
- linux就是这个范儿之特种文件系统(4)
- finally的注意事项一
- ++a和a++
- 5、(知识篇)IO流(2)
- ListView的数据更新问题
- 【LeetCode】Two Sum 题解报告
- Win10环境下Openssl的编译安装以及在vs2013上开发环境的搭建
- 第十周项目3——利用二叉树遍历思想解决问题
- Haskell笔记(4)
- HDOJ 4565 So Easy!
- 使用DateFormat类获取系统的当前时间
- 洛谷 P2409 Y的积木
- 把牌分成两堆,让每堆面朝上的牌数目相同
- poj3980取模运算