LeetCode001-Two Sum(兩數之和)

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].

思路

此題目實際考察的爲哈希表的使用,遍歷數組的時候,將已經遍歷過的元素放進哈希表(key爲數組元素,value爲數組索引)。這樣在遍歷到 nums[i] 時,判斷一下哈希表中是否存在 target-nums[i] 即可。

  • 時間複雜度:O(n)
  • 空間複雜度:O(n)

Java實現

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

Python實現

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        map = {}
        for i in range(len(nums)):
            t = target - nums[i]
            if map.get(t) is not None:
                return [map.get(t), i]
            map[nums[i]] = i

Scala實現

object Solution {
    def twoSum(nums: Array[Int], target: Int): Array[Int] = {
        var map = Map[Int, Int]()
        var t = 0
        for (i <- Range(0,nums.length)) {
            t = target - nums(i)
            if (map.contains(t)) {
                return Array(map(t), i)
            }
            map += nums(i) -> i
        }
        return null
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章