LeetCode------Two Sum
2016-04-05 22:04
495 查看
题目说明
Given an array of integers, return indices of the two numbers such that they add up to a specific target. 给定一个整数的数组,将它们添加到一个特定的目标的2个数字的返回值。
You may assume that each input would have exactly one solution.
你可以假设每个输入都有一个解决方案。
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.
返回的格式已被改为零为基础的索引
自己的解法
自己的想法2个循环 思路很简单但是时间复杂度很高public class Solution { public int[] twoSum(int[] nums, int target) { int[] result=new int[2]; int count=0; for(int i=0;i<nums.length;i++) for(int j=i+1;j<nums.length;j++){ count = nums[i] + nums[j]; if(count == target){ result[0]=i; result[1]=j; } } return result; } }
第一次写的时候在if里面return一直报错,后面查询了下才知道错误是不能在每个条件下都返回值。所以放到了外面,但是要把所有循环都走完,时间复杂度很高,改进版如下
public class Solution { public int[] twoSum(int[] nums, int target) { int[] result=new int[2]; int count=0; for(int i=0;i<nums.length;i++) for(int j=i+1;j<nums.length;j++){ count = nums[i] + nums[j]; if(count == target){ result[0]=i; result[1]=j; return result; } } return result; } }
Hot解法
最后看了一下hot里面java最热的解法public class Solution { public int[] twoSum(int[] numbers, int target) { int[] result = new int[2]; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < numbers.length; i++) { if (map.containsKey(target - numbers[i])) { result[1] = i; result[0] = map.get(target - numbers[i]); return result; } map.put(numbers[i], i); } return result; } }
这里主要使用了java中的Map接口,这里对Map接口做一下简要说明。我自己的理解是Map中存放的就是键值对,主要用法有如下
1.声明一个Map :
Map map = new HashMap();
2 .向map中放值 ,注意: map是key-value的形式存放的,如:
map.put(“sa”,”dd”);
3 .从map中取值 :
String str = map.get(“sa”).toString,
结果是: str = “dd’
4 .遍历一个map,从中取得key和value :
Map m= new HashMap();
for(Object obj : map.keySet()){
Object value = map.get(obj );
}
5.判断Map集合对象中是否包含指定的键名。如果Map集合中包含指定的键名,则返回true,否则返回false。
boolen A=map.containsKey(sa);
这里A为true。
这个解法的时间复杂度为O(n),但是消耗了一定的空间,以时间换取空间。
相关文章推荐
- 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++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树