优秀的程序猿解题之LeetCode 第一题:Two Sum

Tips:所有代码实现包含三种语言(java、c++、python3)

题目

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.

给定数组,返回数组中相加等于给定数的两个数的位置。

可假设仅有一个解,注意数组中的每个数仅可使用一次。

样例

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

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

解题

首先看到:

输入:一个数组(nums)和一个数(target);

输出:由数组(nums)的两个索引组成的新数组,其中这两个索引对应的数满足相加等于数(target);

优秀的程序猿很快理解了问题,然后迅速的把问题转化成计算机好理解的问题:

对于数组(nums)中每个数(temp),求数组中是否存在数x(x满足x = target - temp);

不假思索,优秀的程序猿瞬间想到了暴力遍历法

对数组每个数,遍历查找数组中此数之后的数是否存在此数的补集。

注意:当我们找到一个解之后就可以立即返回了,因为题目中提到了可假设仅有一个解

// java
/* 
Runtime: 20 ms, faster than 41.25% of Java online submissions for Two Sum.
Memory Usage: 38.5 MB, less than 44.37% of Java online submissions for Two Sum.
*/
public int[] twoSum(int[] nums, int target){
    int length = nums.length;
    for (int i = 0; i < length - 1; i++){
        for (int j = i + 1; j < length; j++){
            if (nums[i] + nums[j] == target){
                return new int[]{i, j};
            }
        }
    }
    return null;
}
// c++
/*
Runtime: 136 ms, faster than 36.44% of C++ online submissions for Two Sum.
Memory Usage: 9.5 MB, less than 79.36% of C++ online submissions for Two Sum.
*/
vector<int> twoSum(vector<int>& nums, int target) {
    for(int i = 0; i < nums.size()-1; i++)
    {
        for(int j = i+1; j < nums.size(); j++)
        {
            if(nums[i] + nums[j] == target){
                return {i, j};
            }
        }
    }
    return {};
}
# python3
# Runtime: 5528 ms, faster than 11.87% of Python3 online submissions for Two Sum.
# Memory Usage: 13.5 MB, less than 49.67% of Python3 online submissions for Two Sum.
def twoSum(self, nums: List[int], target: int) -> List[int]:
    for i in range(len(nums)-1):
        for j in range(i+1, len(nums)):
            if nums[i] + nums[j] == target:
                return [i,j]
    return None

不幸的是,可以看到,这个方法的表现比较差,仅 Runtime 来说,处理中下游,优秀的程序猿当然不仅满足于此;

优秀的程序猿继续思考着优化方案,再看一遍问题:

对于数组(nums)中每个数(temp),求数组中是否存在数x(x满足x = target - temp);

优秀的程序猿此时敏感得发现这其中包含一个非有序查找问题,对于非有序查找问题的立马联想到了map;

想到这里,第二个解决方案就出炉了:

  1. 将数组转化成一个map,其中键为数组中的数,值为该数对应得索引值;
  2. 对于数组(nums)中每个数(temp),查找map中是否存在等于(target-temp)的键,如果存在,返回该键对应的值以及当前数的索引值;

注意:如果当前数等于target的一半,那么当前数的补集就是其本身,因为题目要求数组中的每个数仅可使用一次,此时需判断当前数的补集不是其本身。

// java
/*
Runtime: 3 ms, faster than 99.77% of Java online submissions for Two Sum.
Memory Usage: 39.9 MB, less than 5.16% of Java online submissions for Two Sum.
*/
public int[] twoSum(int[] nums, int target){
    int length = nums.length;
    Map<Integer, Integer> numsMap = new HashMap<>();
    for (int i = 0; i < length; i++){
        numsMap.put(nums[i], i);
    }
    for (int i = 0; i< length; i++){
        int complement = target - nums[i];
        if (numsMap.containsKey(complement) && numsMap.get(complement) != i){
            return new int[]{i, numsMap.get(complement)};
        }
    }
    return null;
}
// c++
/*
Runtime: 12 ms, faster than 97.81% of C++ online submissions for Two Sum.
Memory Usage: 10.6 MB, less than 12.73% of C++ online submissions for Two Sum.
*/
vector<int> twoSum(vector<int>& nums, int target) {
    unordered_map<int, int> numsMap; 
    for(int i = 0; i < nums.size(); i++)
    {
        numsMap[nums[i]] = i;
    }
    for(int i = 0; i < nums.size(); i++)
    {
        if(numsMap.count(target-nums[i]) && numsMap[target-nums[i]] != i){
            return {numsMap[target-nums[i]], i};
        }
    }
    return {};
}
# python3
# Runtime: 40 ms, faster than 73.58% of Python3 online submissions for Two Sum.
# Memory Usage: 15.2 MB, less than 5.08% of Python3 online submissions for Two Sum.
def twoSum(self, nums: List[int], target: int) -> List[int]:
    nums_dict = {}
    for i, num in enumerate(nums):
        nums_dict[num] = i
    for i, num in enumerate(nums):
        if (target-num) in nums_dict and i != nums_dict[target-num]:
             return [i, nums_dict[target-num]]
    return None

不愧是一个优秀的程序猿,这个Runtime表现让我们很是欣慰(Memory Usage 很大是因为我们使用了额外的map 存储数据),忍不住的想要多看几遍这优美的代码;

突然,优秀的程序猿发现了在上面的解法中存在两个问题,

  1. 在查找每个数的补集是否存在的时候面向的是整个map,虽然对于 hashmap 来说这不太影响性能,但是也多了一项判断补集不是其本身啊!!!
  2. 算法中先实现了将数据填充至map,然后再逐一查询,那么时间复杂度是O(2n),虽然O(n)和O(2n)是基本一样的,但是能不能再优化一下呢?可以做到边填充边搜索吗???

优秀的程序猿不容许这样的瑕疵存在,经过短暂的思考,又一个思路浮现了出来:

  1. 创建一个空 map;
  2. 对于数组(nums)中每个数(temp),查找map中是否存在等于(target-temp)的键,如果存在,返回该键对应的值以及当前数的索引值;如果不存在,将该数作为键,其索引作为值,放入map中;

在这个思路中,相当于对于数组中的每个数,其补集的搜索范围是数组中位于此数之前的数,即做到了边填充边搜索,又避免了搜索范围的浪费。

// java
/*
Runtime: 3 ms, faster than 99.77% of Java online submissions for Two Sum.
Memory Usage: 38.7 MB, less than 36.97% of Java online submissions for Two Sum.
*/
public int[] twoSum(int[] nums, int target){
    int length = nums.length;
    Map<Integer, Integer> numsMap = new HashMap<>();
    for (int i = 0; i < length; i++) {
        int complement = target - nums[i];
        if (numsMap.containsKey(complement)){
            return new int[]{i, numsMap.get(complement)};
        }
        numsMap.put(nums[i], i);
    }
    return null;
}
// c++
/*
Runtime: 12 ms, faster than 97.81% of C++ online submissions for Two Sum.
Memory Usage: 10.5 MB, less than 21.80% of C++ online submissions for Two Sum.
*/
vector<int> twoSum(vector<int>& nums, int target) {
    unordered_map<int, int> numsMap; 
    for(int i = 0; i < nums.size(); i++)
    {
        if(numsMap.count(target-nums[i])){
            return {numsMap[target-nums[i]], i};
        }
        numsMap[nums[i]] = i;
    }
    return {};
}
# python3
# Runtime: 40 ms, faster than 73.58% of Python3 online submissions for Two Sum.
# Memory Usage: 14.4 MB, less than 5.08% of Python3 online submissions for Two Sum.
def twoSum(self, nums: List[int], target: int) -> List[int]:
    nums_dict = {}
    for i, num in enumerate(nums):
        if (target-num) in nums_dict:
            return [nums_dict[target-num], i]
        nums_dict[num] = i
    return None

优秀的程序猿又严谨得审视了几遍代码,满意得合上了电脑。。。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,367评论 6 512
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,959评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,750评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,226评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,252评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,975评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,592评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,497评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,027评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,147评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,274评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,953评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,623评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,143评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,260评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,607评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,271评论 2 358

推荐阅读更多精彩内容