当前位置:   article > 正文

LeetCode日记(1)--TWO SUM_class solution {public: vector twosum(vect

class solution {public: vector twosum(vector& nums, int target) { }};

题目描述:

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].

题解:

题目的参数是一个vector和一个target,要求我们返回一个新的vector,新vector的内容保存初始vector中某两个元素加起来等于target的下标。(这里使用C++实现)

 

解法1(蛮力算法,时间复杂度O(n^2):循环遍历vector,然后记录两个符合条件的元素下标。

  1. class Solution {
  2. public:
  3.     vector<int> twoSum(vector<int>& nums, int target) {
  4.         vector<int>result;
  5.         for(int i=0;i<nums.size();i++)
  6.         {
  7.             for(int j=i+1;j<nums.size();j++)
  8.             {
  9.                if(nums[i]+nums[j]==target)
  10.                {
  11.                    result.push_back(i);
  12.                    result.push_back(j);
  13.                }
  14.             }
  15.         }
  16.         return result;
  17.     }
  18. };

解法2(多使用一个哈希表作为记录,时间复杂度O(n)):在进行迭代并将元素插入到表中的同时,我们还会回过头来检查表中是否已经存在当前元素所对应的目标元素。如果它存在,那我们已经找到了对应解,将其返回。

PS:这里的记录表为什么选择哈希表而不用数组,是因为查找的时候哈希表的效率比数组快,在查询表中是否已经存在满足条件的元素的时候,哈希表只需要o(1)的时间复杂度,而数组要o(n)。所以如果使用数组的话,时间复杂度和蛮力算法实际上是一样的。

  1. class Solution {
  2. public:
  3. vector<int>twoSum(vector<int>& nums, int target) {
  4. map<int,int>result;
  5. vector<int>v;
  6. for(int i=0;i<nums.size();i++)
  7. {
  8. int temp = target-nums[i];
  9. if(result.find(temp)!= result.end())
  10. {
  11. v.push_back(result[temp]);
  12. v.push_back(i);
  13. }
  14. result[nums[i]]=i;
  15. }
  16. return v;
  17. }
  18. };

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/460961
推荐阅读
相关标签
  

闽ICP备14008679号