【Leetcode】1. Two Sum

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。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值