1. 程式人生 > 實用技巧 >[Leetcode]1. Two Sum

[Leetcode]1. Two Sum

題目描述

Given an array of integers numsand an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

  • Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
  • Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
  • Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]

給定一個數組和目標值,求陣列中兩個值相加等於目標值的索引下標,只會有一個解,且同一個陣列元素不能使用兩次。
本題主要考察雜湊表的用法。

java解法

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

class Solution {

  public int[] twoSum(int[] nums, int target) {
    //key為值,value為陣列下標
    Map<Integer, Integer> map = new HashMap<>();
    int[] res = new int[2];
    for (int i = 0; i < nums.length; i++) {
      int rest = target - nums[i];
      if (map.containsKey(rest)) {
        res[0] = i;
        res[1] = map.get(rest);
        break;
      }
      map.put(nums[i], i);
    }
    return res;
  }

  public static void main(String[] args) {
    System.out.println(Arrays.toString(new Solution().twoSum(new int[]{2, 7, 11, 15}, 9)));
    System.out.println(Arrays.toString(new Solution().twoSum(new int[]{3, 2, 4}, 6)));
    System.out.println(Arrays.toString(new Solution().twoSum(new int[]{3, 3}, 6)));
  }
}

javascript解法

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function (nums, target) {
  var map = {};
  for (var i = 0; i < nums.length; i++) {
    var rest = target - nums[i];
    if (map[rest] !== undefined) {
      return [i, map[rest]];
    }
    map[nums[i]] = i;
  }
  return [];
};

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)):
            rest = target - nums[i]
            if rest in map:
                return [i, map.get(rest)]
            map[nums[i]] = i
        return []