leetcode学习之路-Two Sum

来源:互联网 发布:怎么查看淘宝抢购排名 编辑:程序博客网 时间:2024/05/18 13:25

question1:Two Sum
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.
update:The return format had been changed to zero-based indices. Please read the above updated description carefully.

Example:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].

Brute Force(O(N^2)):

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        int i,j;        for(i = 0; i < nums.size(); ++i) //vector没有length()方法,string有        {            for(j = i+1; j < nums.size(); ++j)              {                if(nums[i] + nums[j] == target) return vector<int>{i,j};  //此处为列表初始化返回值(c++11),也可直接{i,j}            }        }        return vector<int>{}; //也可直接return {}    }};

One-Pass hashTable(O(N)):

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        map<int,int> hashMap;        for(int i = 0; i < nums.size(); ++i)        {            if(hashMap.count(target - nums[i])) return {hashMap[target-nums[i]], i};            hashMap[nums[i]] = i;  //map的下标运算符返回关键字-值对的值,此处将关键字设为vector的元素,值设为vector的下标        }        return {};    }};

还有一种hashTable的方法,即先将所有元素都录入map,然后再遍历寻找target-nums[i]是否在map中。如果是,返回两个关键字的值。此处需要注意两个关键字不能相同,即hashMap[target-nums[i]] != i.所以,此方法输于One-Pass方法。

0 0
原创粉丝点击