[leetcode]1.Two Sum

来源:互联网 发布:csgo数据互换器永久 编辑:程序博客网 时间:2024/06/05 19:11

题目链接:https://leetcode.com/problems/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

思路:

第一种:两重循环搜索所有的情况,时间复杂度是O(n*n),估计是过不了测试数据的。

第二种:将数组排序,然后两个指针从左右分别扫描数组:

1)如果当前和大于target,则右指针左移一位;

2)如果当前和小于target,则左指针右移一位

这种方法需要排序和记录原数组中数的坐标,并且得到的index仍然需要排序放入结果中。时间复杂度是O(n*log(n)),这是排序的复杂度。

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        if(nums.size() < 2) return {};        vector<pair<int,int>> vec;        for(int i = 0;i < nums.size();i++)            vec.push_back(make_pair(nums[i],i));        sort(vec.begin(),vec.end());        int left = 0,right = nums.size()-1;        while(left < right){            int val = vec[left].first + vec[right].first;            if(val == target) return vector<int>{vec[left].second,vec[right].second};            else if(val > target) right--;            else left++;        }        return {};    }};

第三种:将原数组中的数放到hash表中,然后扫描一遍即可,很方便。时间复杂度为O(n). 这种方法有一个限制就是不能有重复解.还有注意的是如果一个数可以分解为两个相同数的和的情况。

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        unordered_map<int,int> hash;        for(int i=0;i<nums.size();i++)            hash[nums[i]]=i;        for(int i=0;i<nums.size();i++)            if(hash.count(target-nums[i])&&hash[target-nums[i]]!=i)                return vector<int>{i,hash[target-nums[i]]};        return vector<int>(0);    }};
原创粉丝点击