【leetcode】1. Two Sum

来源:互联网 发布:东华软件股票行情 编辑:程序博客网 时间:2024/05/16 06:24

一、题目描述

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.

Example:

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

UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.


题目解读:给一个整数序列和一个目标值,找出序列中两个数加起来等于目标值,返回这两个数在序列中的下标


思路:一开始只能想到写两个for循环遍历


c++代码(758ms,11.48%) 就这样还能排到11%呢  = = ! 汗....

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        vector<int> result;        int left,right;        for(left=0; left<nums.size(); left++){            for(right = left+1; right<nums.size(); right++){                if((nums[left]+nums[right]) == target){                    result.push_back(left);                    result.push_back(right);                    return result;                }//if            }//for        }//for        return result;    }};


看讨论区别人的代码,在遍历的同时使用map存储已遍历过的数的位置,以便于快速查找,时间复杂度可以达到o(n)

c++代码(16ms,62.06%)

class Solution {public:    vector<int> twoSum(vector<int>& numbers, int target) {        //Key is the number and value is its index in the vector.        unordered_map<int, int> hash;        vector<int> result;        for (int i = 0; i < numbers.size(); i++) {        int numberToFind = target - numbers[i];                            //if numberToFind is found in map, return them        if (hash.find(numberToFind) != hash.end()) {                            //+1 because indices are NOT zero based        result.push_back(hash[numberToFind]);        result.push_back(i);        return result;        }                            //number was not found. Put it in the map.        hash[numbers[i]] = i;        }        return result;    }};


0 0
原创粉丝点击