[Leetcode]1. Two Sum

技术文章 6个月前 完美者
1,973 0

标签:util   example   nbsp   inpu   lang   有一个   value   void   def   

题目描述

Given an array of integers nums and 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 []

[Leetcode]1. Two Sum

标签:util   example   nbsp   inpu   lang   有一个   value   void   def   

原文地址:https://www.cnblogs.com/strongmore/p/14263875.html

版权声明:完美者 发表于 2021-01-13 11:07:09。
转载请注明:[Leetcode]1. Two Sum | 完美导航

暂无评论

暂无评论...