蜗牛慢慢爬 LeetCode 1.Two Sum [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, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

翻译

给定一个整形数组和一个整数target,返回2个元素的下标,它们满足相加的和为target。
你可以假定每个输入,都会恰好有一个满足条件的返回结果。

Hints

Related Topics: Array, Hash Table
如果简单地想O(n^2)的算法很容易实现
但是可以利用Hash Table来实现O(n)的算法

代码

Java

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

//solution from discuss
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 + 1;
                result[0] = map.get(target - numbers[i]);
                return result;
            }
            map.put(numbers[i], i + 1);
        }
        return result;
    }
}

Python

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        mymap = {}
        for i in range(len(nums)):
            if nums[i] in mymap:
                return [mymap[nums[i]],i]
            else:
                mymap[target-nums[i]] = i
        return [0,0]
        
原文地址:https://www.cnblogs.com/cookielbsc/p/7427909.html