LeetCode------Two Sum

题目说明

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),但是消耗了一定的空间,以时间换取空间。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值