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    };

 

posted @ 2019-07-13 19:28  Let_Life_Stop  阅读(126)  评论(0编辑  收藏  举报