1. Two Sum 两数和

题目链接
tag:

  • Easy;

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

思路:
  本道题给一个数组,一个目标数target,让我们找到两个数字,使其和为target,第一感觉暴力搜索,但是猜到OJ肯定不会允许用这么简单的方法,于是去试了一下,果然是Time Limit Exceeded,这个算法的时间复杂度是O(n^2)。那么只能想个O(n)的算法来实现,由于暴力搜索是遍历所有的两个数字的组合,这样虽然节省了空间,但时间复杂度高。一般来说,我们为了提高时间的复杂度,需要用空间来换,这算是一个trade-off吧,用线性的时间复杂度来解决问题,那么就是说只能遍历一个数字,那么另一个数字呢,我们可以事先将其存储起来,使用一个HashMap,来建立数字和其坐标位置之间的映射,HashMap是常数级的查找效率,这样,我们在遍历数组的时候,用target减去遍历到的数字,就是另一个需要的数字了,直接在HashMap中查找其是否存在即可,注意要判断查找到的数字不是第一个数字,比如target是4,遍历到了一个2,那么另外一个2不能是之前那个2,整个实现步骤为:先遍历一遍数组,建立HashMap映射,然后再遍历一遍,开始查找,找到则记录index。代码如下:

C++ 解法:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        // 两次遍历+哈希
        vector<int> res;
        unordered_map<int, int> m;
        if (nums.size() < 2)
            return res;
        for (int i=0; i<nums.size(); ++i)
            m[nums[i]] = i;
        for (int i=0; i<nums.size(); ++i) {
            int tmp = target - nums[i];
            if (m.count(tmp) && m[tmp] != i) {
                res.push_back(i);
                res.push_back(m[tmp]);
                break;
            }
        }
        return res;
    }
};
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        // 一次遍历+哈希
        vector<int> res;
        if (nums.size() < 2) {
            return res;
        }
        unordered_map<int, int> m;
        for (int i = 0; i < nums.size(); ++i) {
            int tmp = target - nums[i];
            if (m.count(tmp) && m[tmp] != i) {
                res.push_back(i);
                res.push_back(m[tmp]);
                break;
            }
            m[nums[i]] = i;
        }
        return res;
    }
};

Python 解法:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        res = []
        if len(nums) < 2:
            return res
        m = {}
        for i in range(len(nums)):
            m[nums[i]] = i
        for i in range(len(nums)):
            diff = target - nums[i]
            if diff in m.keys() and (i != m[diff]):
                res.append(i)
                res.append(m[diff])
                break
        return res
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容