【Leetcode】1. Two Sum
2016-07-08 11:34
585 查看
1. Two Sum
Total Accepted: 254411Total 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。
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c语言实现hashmap(转载)
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序