• LeetCode 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] + nums[1] = 2 + 7 = 9,
    return [0, 1].

    题目的意思不理解,求数组中是否存在两个数之和等于给定的数,并且返回两个数的下标,注意返回的是下标,而且从给定的结果来看要求下标的顺序和数字在数组中出现的顺序相对应。
    首先一个直接的思路就是穷举,代码如下:
     1 class Solution {
     2 public:
     3     vector<int> twoSum(vector<int>& nums, int target) {
     4         int size=nums.size();
     5         vector<int>  result;
     6         for(int i=0;i<size-1;i++)
     7         {
     8               for(int j=i+1;j<size;j++)
     9               {
    10                   if(nums[i]+nums[j]==target)
    11                   {
    12                       result.push_back(i);
    13                       result.push_back(j); 
    14                   } 
    15                   
    16               }
    17         }    
    18                 
    19         return result;
    20     }
    21 };
    
    

    可以AC,但是时间复杂度为O(n^2),需要改进

    如果题目只要求返回数字,可以考虑使用sort直接对原来的向量进行排序,然后放置一头一尾两个指针解决问题,时间复杂度O(n*logn)

    这道题最直接的思路是构建hash表,利用map容器完成,代码如下:

     1 class Solution {
     2 public:
     3     vector<int> twoSum(vector<int>& nums, int target) {
     4     map<int, int> hash;
     5     vector<int> result;
     6     for (int i = 0; i < nums.size(); i++) {
     7         int numberToFind = target - nums[i];
     8         if (hash.find(numberToFind) != hash.end()) {
     9             result.push_back(hash[numberToFind]);
    10             result.push_back(i);            
    11             return result;
    12         }
    13 
    14             //number was not found. Put it in the map.
    15         hash[nums[i]] = i;
    16     }
    17     return result;
    18     }
    19 };

     一刷(2018.01.25):各种出错,忘记target减去nums[i],忘记push_back(hash[numberToFind])

     
  • 相关阅读:
    为了博多
    [JSOI2008]星球大战starwar
    【网络流24题】最小路径覆盖问题
    【中学高级水题本】关路灯
    【网络流24题】分配问题
    【网络流24题】方格取数问题
    【网络流24题】汽车加油行驶
    [洛谷P2057][bzoj1934]善意的投票(最大流)
    LeetCode(38) Count and Say
    LeetCode(36)Valid Sudoku
  • 原文地址:https://www.cnblogs.com/dapeng-bupt/p/7874228.html
Copyright © 2020-2023  润新知