1. Two Sum - Easy - Leetcode

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 sameelement twice.

Example:

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

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

Related Topic: Array, Hash Table

解题思路:这是LC一道经典题,考虑使用HashMap来保存input中值与其数组index的对应关系。在遍历数组的过程中,若target减去当前遍历值在HashMap中存在,则证明已找到对应的两个值,找到其index返回结果即可,反之则将当前遍历点写入HashMap。

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

Java版本:

 1 class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         int[] result = new int[2];
 4         if (nums == null || nums.length < 2) {
 5             return result;
 6         }
 7
 8         Map<Integer, Integer> map = new HashMap<Integer, Integer>();
 9
10         for (int i = 0; i < nums.length; i++) {
11             if (map.containsKey(target - nums[i])) {
12                 result[0] = map.get(target - nums[i]);
13                 result[1] = i;
14             }
15             map.put(nums[i], i);
16         }
17
18         return result;
19     }
20 }

JavaScript版本:

 1 /**
 2  * @param {number[]} nums
 3  * @param {number} target
 4  * @return {number[]}
 5  */
 6 var twoSum = function(nums, target) {
 7     var result = new Array(2);
 8     if (nums == null || nums.length < 2) {
 9         return result;
10     }
11
12     var map = new Map();
13
14     for (var i = 0; i < nums.length; i++) {
15         if (map.has(target - nums[i])) {
16             result[0] = map.get(target - nums[i]);
17             result[1] = i;
18         }
19         map.set(nums[i], i);
20     }
21
22     return result;
23 };

Python版本:

 1 class Solution:
 2     def twoSum(self, nums: List[int], target: int) -> List[int]:
 3         result = [None] * 2
 4         if len(nums) < 2:
 5             return result
 6
 7         dict = {}
 8
 9         for i in range(len(nums)):
10             if (target - nums[i]) in dict:
11                 result[0] = dict.get(target - nums[i])
12                 result[1] = i
13
14             dict[nums[i]] = i
15
16         return result

原文地址:https://www.cnblogs.com/raymondwang/p/10887505.html

时间: 2024-07-30 12:50:40

1. Two Sum - Easy - Leetcode的相关文章

LeetCode--Array--Two sum (Easy)

1.Two sum (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

Combination Sum II leetcode java

题目: Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. Each number in C may only be used once in the combination. Note: All numbers (including target) will be

Path Sum II leetcode java

题目: Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example: Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ / 7 2 5 1 return [ [5,4,11,2], [5,8,4,5] ] 题解: 这道题除了要判断是否有这样的一个p

【leetcode】Minimum Path Sum(easy)

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. 思路:由于只能向两个方向走,瞬间就没有了路线迂回的烦恼,题目的难度

Leetcode 1. Two Sum (Easy)

Description 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

Path Sum II -- leetcode

For example: Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ / 7 2 5 1 return [ [5,4,11,2], [5,8,4,5] ] 基本思路: 深度递归. 逐层从sum中扣去当节点的val值. 到叶结点时,检查sum值是否等于该叶结点的val值.若是,则找到一个结果. 在结果集中,用最后一个元素,作为待决结果.随着栈的深入而压入元素,退出则弹出元素. 在leetcode上实际执行时间为

Path Sum III Leetcode

You are given a binary tree in which each node contains an integer value. Find the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to

(easy)LeetCode 204.Count Primes

Description: Count the number of prime numbers less than a non-negative number, n. Credits:Special thanks to @mithmatt for adding this problem and creating all test cases. 解析:大于1的自然数,该自然数能被1和它本身整除,那么该自然数称为素数. 方法一:暴力破解,时间复杂度为O(N^2) 代码如下: public class

Combination Sum II —— LeetCode

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. Each number in C may only be used once in the combination. Note: All numbers (including target) will be posi