Two sum 两数之和

来源:互联网 发布:linux查看oracle版本 编辑:程序博客网 时间:2024/06/06 18:44

给定一个数组和一个特定的数,使得数组中的两个数等于这个特定的数。找出这两个数的下标。

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

class Solution {public:    vector<int> twoSum(vector<int> &numbers, int target){         vector<int> res;        if(numbers==null||numbers.length<2)            return res;        //copy original list and sort        vector<int> res copylist ;          copylist.assign(numbers.begin(),numbers.end());        copylist.sort(copylist.begin(),copylist.end());        int low = 0;        int high = copylist.size()-1;        while(low<high){            if(copylist[low]+copylist[high]<target)                low++;            else if(copylist[low]+copylist[high]>target)                high--;            else{                res[0]=copylist[low];                res[1]=copylist[high];                break;            }        }        //find index from original list        int index1 = -1, index2 = -1;          for(int i = 0; i < numbers.size(); i++){              if(numbers[i] == res[0]&&index1==-1)                index1 = i+1;            else if(numbers[i] == res[1]&&index2==-1)                index2 = i+1;       }         res[0] = index1;        res[1] = index2;        res.sort(res.begin(),res.end());        return res;    }
class Solution {public:    vector<int> twoSum(vector<int> &numbers, int target)    {        int i, sum;          vector<int> results;          map<int, int> hmap;          for(i=0; i<numbers.size(); i++){              if(!hmap.count(numbers[i])){                  hmap.insert(pair<int, int>(numbers[i], i));              }              if(hmap.count(target-numbers[i])){                  int n=hmap[target-numbers[i]];                  if(n<i){                      results.push_back(n+1);                      results.push_back(i+1);                      //cout<<n+1<<", "<<i+1<<endl;                      return results;                  }              }          }          return results;      }};
class Solution {public:    vector<int> twoSum(vector<int> &numbers, int target) {        map<int, int> mapping;        vector<int> res;        for (int i = 0; i < numbers.size(); ++i) {            mapping[numbers[i]] = i;        }        for (int i = 0; i < numbers.size(); i++) {            int searched = target - numbers[i];            if (mapping.find(searched) != mapping.end() && i != mapping[searched]) {                res.push_back(i + 1);                res.push_back(mapping[searched] + 1);                break;            }        }        return res;    }};
原创粉丝点击