leetcode第一题

转载 2016年05月31日 11:16:39

以下为转载:

Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

 

首先,不能对该数组作任何预处理。因为要求返回是原始数组的下标,如果对数组进行了排序,那么下标就会乱。

(如果是有序数组,可以用双指针来做,参见Two Sum II - Input array is sorted

很容易想到用<value, index>的映射表。

遍历numbers,在映射表中寻找target-numbers[i].

若找到则结束,返回存储的下标+1和当前下标+1. (注意题目中规定,以1作为起始下标)

若找不到则将<numbers[i], i>加入映射表。

这里又有一个问题,C++中常用的映射表有map, unordered_map。

根据http://www.cplusplus.com/reference/上面的说明我们来比较差异:

map:

Internally, the elements in a map are always sorted by its key following a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare).

map containers are generally slower than unordered_map containers to access individual elements by their key, but they allow the direct iteration on subsets based on their order.

map::operator[]:

Logarithmic in size.

unordered_map:

复制代码
Internally, the elements in the unordered_map are not sorted in any particular order with respect to either their key or mapped values, but organized into buckets depending on their hash values to allow for fast access to individual elements directly by their key values (with a constant average time complexity on average).

unordered_map containers are faster than map containers to access individual elements by their key, although they are generally less efficient for range iteration through a subset of their elements.
复制代码

unordered_map::operator[]:

Average case: constant.
Worst case: linear in container size.

本题只需要根据key访问单个元素,因此unordered_map更合适。

时间复杂度O(n):一次遍历

空间复杂度O(n):unordered_map

ps: 严格来说,target-numbers[i]可能溢出int,因此提升为long long int更鲁棒。

复制代码
class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        vector<int> ret(2,-1);
        unordered_map<int, int> m;    //value->index map
        for(int i = 0; i < numbers.size(); i ++)
        {
            if(m.find(target-numbers[i]) == m.end())
            //target-numbers[i] not appeared
                m[numbers[i]] = i;
            else
            {
                ret[0] = m[target-numbers[i]]+1; 
                ret[1] = i+1;
                return ret;
            }
        }
    }
};
复制代码

leetcode的c++实现(一)

说在前面的话:c++的书看了几遍,但是平时写的机会比较少,所以忘得很快,俗话说读万卷书行万里路,没有实践理论的东西都是浮云。正好leetcode给我们提供了一个温故而知新的平台,我就计划借助这个平台在...
  • l_b_yuan
  • l_b_yuan
  • 2016年04月28日 19:23
  • 1316

leetcode第一题

原题: Given an array of integers, find two numbers such that they add up to a specific target number....
  • but6565
  • but6565
  • 2016年02月19日 10:50
  • 78

LeetCode 第一题剪彩自己的leetCode之路

Reverse Words in a String   Given an input string, reverse the string word by word. For e...
  • q745401990
  • q745401990
  • 2014年08月18日 16:01
  • 1050

每天一题LeetCode[第四天]

每天一题LeetCode[第四天]Add Two NumbersDescription:You are given two non-empty linked lists representing tw...
  • qq_23843415
  • qq_23843415
  • 2017年02月06日 22:43
  • 61

关于LeetCode算法题,第一题

题目链接:https://oj.leetcode.com/problems/maximum-product-subarray/ 题目介绍: Find the contiguous suba...
  • jianggest
  • jianggest
  • 2015年01月07日 11:36
  • 284

LeetCode第一题就悲剧了

Given an array of integers, every element appears twice except for one. Find that single one. Not...
  • why2011me
  • why2011me
  • 2015年04月07日 21:49
  • 159

每天一题LeetCode[第十天]

每天一题LeetCode[第十天]3SumDescription:Given an array S of n integers, are there elements a, b, c in S suc...
  • qq_23843415
  • qq_23843415
  • 2017年02月19日 00:45
  • 83

leetcode算法第一题

LEETCODE算法汇总最近一直刷算法题,努力提高自身的算法功底.如果学习过程中不总结,很快就忘记了,所以要养成总结习惯,近期会不间断的写一写自己的心得以及对题目的认识.leetcode第一题题目Gi...
  • u014675538
  • u014675538
  • 2017年12月25日 19:52
  • 15

每天一题LeetCode[第五天]

每天一题LeetCode[第五天]Longest Palindrome SubstringDescription:Given a string s, find the longest palindro...
  • qq_23843415
  • qq_23843415
  • 2017年02月07日 18:35
  • 126

每天一题LeetCode[第六天]

每天一题LeetCode[第六天]Reverse IntegerDescription:Reverse digits of an integer.Example1: x = 123, return 3...
  • qq_23843415
  • qq_23843415
  • 2017年02月09日 23:29
  • 73
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode第一题
举报原因:
原因补充:

(最多只允许输入30个字)