算法课程Leetcode作业第一周技术博客

来源:互联网 发布:知几是什么意思 编辑:程序博客网 时间:2024/06/17 00:24

算法课程Leetcode作业第一周技术博客

第一周的作业先尝试下easy难度试试水

题目:No.1 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, and you may not use the same element twice.

Example:

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

分析:

题目描述其实很简单,从给定的vector里面找出两个相加等于target的数的下标,将下标存放在整型vector中作为返回值。
最简单的方法就是用两层嵌套的方式遍历所有组合方式,将两个数和target做比较,直到找到正确的位置后结束嵌套循环,这种算法的时间复杂度是O(n2)

代码:

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

运行结果分析:

image_1bplkrnm914v81j917ufhll2tt9.png-145.8kB
这样的算法虽然简单但是运行时间也是较长的,因此我们尝试以下优化算法

算法优化

分析之前的算法,其最耗时的部分就是需要通过两个循环来找到相加为target的数,通常要优化时间复杂度需要牺牲空间,如果我们能只遍历一遍vector,然后找出第二个的数的位置,就能将O(n2)变成O(n),也就是说找第二个数的时间复杂度为O(1),满足这样条件的数据结构就是哈希表。

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        map<int, int> hash_map;        map<int, int>::iterator it;        int second;        vector<int> final;        for (int i = 0; i < nums.size(); i++) {            it = hash_map.find(target - nums[i]); //此时i不在map里面,不用担心重复??            if (it == hash_map.end()) {                hash_map.insert(pair<int, int>(nums[i], i));            } else {                final.push_back(it -> second);                final.push_back(i);                return final;            }        }        return final;    }};

运行结果

image_1bpls9sbk1jsbcu43qh1i8c1bqt16.png-137.4kB