LeetCode #1 Two Sum 两数之和

1 Two Sum 两数之和

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, 7, 11, 15], target = 9,

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

题目描述:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

思路:

  1. 暴力法: 对每个数, 遍历剩下的数求是否存在解. 时间复杂度O(n^2), 空间复杂度O(1)
  2. 一次遍历哈希法: 建立一个map存放相应元素对应的目标元素, 并在插入的时候检查, 时间复杂度O(n), 空间复杂度O(n)

代码:
C++:

class Solution 
{
public:
    vector<int> twoSum(vector<int>& nums, int target) 
    {
        vector<int> result;
        // key为nums的值, value为nums下标
        map<int, int> int_map;
        for (int i = 0; i < nums.size(); i++) 
        {
            // map.count()测试主键是否存在, 若存在返回1
            if (int_map.count(nums[i]) != 0) 
            {
                // push_back(elem)在容器最后位置添加一个元素elem
                result.push_back(int_map[nums[i]]);
                result.push_back(i);
                break;
            }
            int_map[target- nums[i]] = i;
        }
        return result;     
    }
};

Java:

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

Python:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dic = {}
        for index, num in enumerate(nums):
            complement = target - num
            if complement in dic:
                return [dic[complement], index]
            dic[num] = index
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1.题目描述: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整...
    Jayce_xi阅读 546评论 0 0
  • leetcode 1. 两数之和题目: 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每...
    和尚我不念经阅读 424评论 0 0
  • 问题描述 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并...
    youthcity阅读 656评论 0 51
  • 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的...
    笙绳省盛阅读 305评论 0 1
  • 正文: 同理心是从某个人的角度来体验世界,重新创造个人观点的能力。也许我们不可能完全体会到另一个人的直觉,...
    自如得己阅读 236评论 12 0

友情链接更多精彩内容