第一周 leetcode算法题(easy)之 Two Sum

因为本人代码能力很弱,所以第一周就先找了一道leetcode里面的简单题来试试手,题目如下:

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.

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

第一种最简单的解法:
对这个容器进行一次遍历,对于每一个遍历的元素,再进行一次遍历,将两个数相加,判断得到的和是否与target相符。如果相符,就把这两个元素的下标保存到输出的容器中。
代码实现如下(本题我是用c++做的):

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

算法复杂度分析:这里用到了两个循环,每个循环遍历一次数据,所以时间复杂度为O(n²)。对于本题来说,数据规模较小,还算可以接受。但如果数据规模很大,这种方法就不是很适合了。

第二种方法:
对于第一种方法来说,每一个元素都要查找n次,查询时间的复杂度就为O(n)。这里考虑将查找时间减少,使其复杂度降低为O(1),所以就用到了STL中的map.

Maps are associative containers that store elements formed by a combination of a key value and a mapped value, following a specific order.

In a map, the key values are generally used to sort and uniquely identify the elements, while the mapped values store the content associated to this key.
Maps are typically implemented as binary search trees.
(引用自www.cpluscplus.com)

所以我们可以用一个map来存储数据,将每一个数据值作为key,该数据的序号作为与key相关联的mapped value。由于map查找元素的便利,我们就可以只用一次循环,对于遍历的每一个数据,我们只需要判断与其相加和为target的值存不存在于map中即可,如果存在,那么把这两个key的mapped value输出。代码如下:

class Solution {
public:
    vector<int> twoSum(vector<int> & nums, int target) {
        map<int,int> map;
        for(int i = 0; i < nums.size(); i++) {
            map.insert(pair<int,int>(nums[i], i);
        }
        int complement;
        vector<int> result;
        for(int i = 0; i < nums.size(); i++) {
            complement = target - nums[i];
            if(map.find(complement) != map.end()
               && map[complement] != i) {
                result.push_back(i);
                result.push_back(map.at(complement));
                break;
            }
        }
        return result;
    }
};

算法复杂度分析:本代码用了两个一层循环,时间复杂度为O(n),因为利用map查找元素的时间复杂度只有O(1),所以总的算法时间复杂度变为O(n)。这相当于增大空间复杂度来降低时间复杂度,在某种程度上而言,这种方法是可行的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值