【Leetcode】1. Two Sum
来源:互联网 发布:中国可备案的域名后缀 编辑:程序博客网 时间:2024/05/29 17:25
1. Two Sum
- Total Accepted: 254411
- Total Submissions: 1031847
- Difficulty: 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)
2、hash O(n):Hash表法,以空间换时间:时间复杂度:O(N)空间复杂度O(N).
更快的查找方法:hash表,给定一个数字,根据hash映射查找另一个数字是否在数组中,只需O(1)的时间,但需要承担O(N)的hash表存储空间。
代码1(暴力):
public class Solution { public int[] twoSum(int[] nums, int target) { int index[] = {-1,-1} ; for(int i = 0 ; i < nums.length ; i++){ for(int j = 0 ; j < nums.length ; j++){ if(nums[j] == target - nums[i]){ index[0] = i; index[1] = j; break; } } if(index[0] != -1 && index[1] != -1 && index[0] != index[1]) break; } return index; }}
Runtime: 58 ms
代码2(hash):
public class Solution {public int[] twoSum(int[] numbers, int target) {if (numbers != null) {HashMap<Integer, Integer> num_map = new HashMap<Integer, Integer>();for (int i = 0; i < numbers.length; i++) {if (num_map.containsKey(numbers[i])) {int index = num_map.get(numbers[i]);int[] result = { index, i };return result;} else {num_map.put(target - numbers[i], i);}}}return null;}}Runtime: 6 ms
分析:
遍历传进来的数组int[] numbers,检查target - numbers[i]在不在hash表中,target - number[i]存储为hash表的key。如果在,就返回当前的i,和对应的key。
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
- 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
- VC6.0 Window7结束调试时程序无法结束的问题解决办法
- HDU 2188 悼念512汶川大地震遇难同胞――选拔志愿者(巴什博奕)
- 【iOS】iOS下高斯模糊效果的实现
- 快照技术原理
- Kaggle 手写识别题
- 【Leetcode】1. Two Sum
- 关于mybatis like
- yield 是什么?
- spring中的@Configration详解
- 架构设计:系统间通信(18)——服务治理与Dubbo 下篇(继续分析)
- 新的测试项
- 分布式机器学习框架:MxNet 前言
- IT自由职业者的赚钱利器
- 常使用的宏定义归类(新添加的一些)