1. Two Sum

题目:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

链接: http://leetcode.com/problems/two-sum/

题解:

使用HashMap,一次遍历数组。 

Time Complexity - O(n),Space Complexity - O(n)

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int result[] = {-1, -1};
        if(numbers == null || numbers.length == 0)
            return result;
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i = 0; i < numbers.length; i++){
            if(!map.containsKey(target - numbers[i]))
                map.put(numbers[i], i);
            else{
                result[0] = map.get(target - numbers[i]) + 1;
                result[1] = i + 1;
                break;
           }    
        }
        return result;
    }
}

 

或者可以先sort数组,再用双指针找target - numbers[i]。这样的话Time Complexity 应该是是O(nlogn), Space Complexity是O(n),就是时间复杂度换空间复杂度。 要注意sort之后原数组的index也会改变,要找到好的方法保存原数组的index。

Python:

Time Complexity - O(n), Space Complexity - O(n)

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if len(nums) <= 1:
            return False
        dict = {}
        
        for i, num in enumerate(nums):
            if target - num in dict:
                return dict[target - num] + 1, i + 1
            else:
                dict[num] = i

        return -1, -1

 

Update:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if (nums is None) or (len(nums) < 2):
            return -1, -1
        dict = {}
        
        for i, num in enumerate(nums):
            if target - num in dict:
                return dict[target - num] + 1, i + 1
            else:
                dict[num] = i
        
        return -1, -1
        

 

二刷: 

Java: 

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[] {-1, -1};
        if (nums == null || nums.length == 0) {
            return res;
        }
        Map<Integer, Integer> map = new HashMap<>();
        
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                res[0] = map.get(target - nums[i]) + 1;
                res[1] = i + 1;
                return res;
            } else {
                map.put(nums[i], i);
            }
        }
        
        return res;
    }
}

 

Python:

发现检测元素是否在dict中用 in dict比用in dict.keys()快十倍,不清楚为什么

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dict = {}
        for i, num in enumerate(nums):
            if target - num in dict:
                return (dict[target - num] + 1, i + 1)
            else:
                dict[num] = i
        return (-1, -1)
                
                

 

三刷:

3/7/2016. 

有可能要考虑一下正负数的溢出

Java:

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        if (nums == null || nums.length == 0) {
            return res;
        }
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                res[0] = map.get(target - nums[i]);
                res[1] = i;
                return res;
            }
            map.put(nums[i], i);
        }
        return res;
    }
}

 

Reference:

http://www.cnblogs.com/springfor/p/3859618.html

posted @ 2015-04-15 11:08  YRB  阅读(623)  评论(1编辑  收藏  举报