您的位置:首页 > 编程语言 > Java开发

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),但是消耗了一定的空间,以时间换取空间。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息