Two Sum

题目:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

解法一:遍历,时间O(n2)

代码如下:

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> result(2);
        if(numbers.size()<=0)
            return result;
        for(int i=0;i<numbers.size();i++)
        {
            int num = target-numbers[i];
            for(int j=i+1;j<numbers.size();j++)
            {
                if(numbers[j]==num)
                {
                    result[0] = i+1;
                    result[1] = j+1;
                    return result;
                }
            }
        }
        return result;
    }
};


解法二:先排序O(nlogn),在遍历O(n),时间复杂度为O(nlogn)

因为我们要知道元素的位置,所以我们排序时,需要记下该元素的初始索引index。

 

typedef struct node{      int val;      int ind;      node(){};      node(int v, int i) : val(v), ind(i){}  }Node;

 

bool comp(const Node & anode,const Node & bnode) {     return (anode.val<bnode.val); }

 

class Solution { public:     vector<int> twoSum(vector<int> &numbers, int target) {         // Start typing your C/C++ solution below         // DO NOT write int main() function         vector<int> result(2);         if(numbers.size()<=0)             return result;         int len = numbers.size();         vector<Node> myvector(len);         for(int i=0;i<len;i++)             myvector[i] = Node(numbers[i],i);         sort(myvector.begin(),myvector.end(),comp);           int i=0, j=len-1;         while(i<=j)         {             int left = myvector[i].val;             int right = myvector[j].val;             if(left+right==target)             {                 result[0] = min(myvector[i].ind,myvector[j].ind)+1;                 result[1] = max(myvector[i].ind,myvector[j].ind)+1;                 break;             }             else if(left+right<target)                      i++;                  else                      j--;         }         return result;     } };

这里空间复杂度是 O(n) ,时间复杂度是O(nlogn)。

解法三: 用Hash的思想,实现快速查表,可达到O(N)

具体关于 HashTable 的实现可以用 Map 数据结构 来实现,具体参考 博文 Hash Table的实现

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> result(2);
        if(numbers.size()<=0)
            return result;
        int len = numbers.size();
        map<long, int> hashTable;
        for(int i=0;i<len;i++)
        {
            int ind = (target-numbers[i])*numbers[i];
            if(hashTable[ind]>0)
            {
                if(numbers[i]+numbers[hashTable[ind]-1]==target)
                {
                    result[0] = hashTable[ind];
                    result[1] = i+1;
                    break;
                }
            }
            else
                hashTable[ind] = i+1;
        }
        return result;
    }
};


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值