• Two Sum


    题目连接:https://leetcode-cn.com/problems/two-sum/

    题目大意:

    找出两个数,相加等于给定的值。

    AC代码:

     1 class Solution {
     2 public:
     3    vector<int> twoSum(vector<int>&nums, int target) {
     4         for (int i = 0;i < nums.size() ;i++ ){
     5           for ( int j = i + 1 ; j < nums.size() ; j++ ){
     6               if(nums[i] + nums[j] == target ){
     7                   vector<int>tmp;
     8                   tmp.push_back(i);
     9                   tmp.push_back(j);
    10                   return tmp;
    11               }
    12           }
    13         }
    14        vector<int>tmp;
    15        return tmp; // 注意即使题目保证一定有解,也要返回一个值
    16 
    17 };

    方法二:

     1  class Solution {
     2    public:
     3       vector<int> twoSum(vector<int>&nums, int target) {
     4         vector<int>ans;
     5         vector<int>mp[1000000+10]; // 搞了一个桶,卡不过去
     6           int len = nums.size();
     7           for (int i = 0 ; i< len ; i++ ){
     8              mp[nums[i]].push_back(i);
     9           }
    10          for( int i = 0 ; i< len ; i++ ){
    11              if(target < nums[i] )continue;
    12               if(nums[i] + nums[i] == target && mp[ nums[i] ].size()>=2){
    13                ans.push_back(mp[nums[i]][0]);
    14                ans.push_back(mp[nums[i]][1]);
    15                   break;
    16               }
    17               if(mp[target - nums[i]].size() >= 1){
    18                 ans.push_back(i);
    19                 ans.push_back(mp[ target - nums[i] ][0]);
    20                   break;
    21               }
    22           }
    23           return ans;
    24       }
    25    };
  • 相关阅读:
    二维数组和二维指针作为函数的参数
    我所理解的tensorflow
    新篇:A New Start
    3NF(Canonical Cover and Decomposition)
    SQL: group by + having
    hihoCoder挑战赛14
    KMP算法
    二分查找
    Cellular Network
    拓撲排序
  • 原文地址:https://www.cnblogs.com/letlifestop/p/11181785.html
Copyright © 2020-2023  润新知