LeetCode OJ:Two Sum

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(nlogn),空间复杂度O(n)

class Solution {
    struct node{
        int val,index;
        node(int x,int y):val(x),index(y){}
    };
    struct cmp{
        bool operator ()(const node &S,const node &T){
            return S.val<T.val;
        }
    };
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        vector<node> store;
        for(int i=0;i<numbers.size();i++)store.push_back(node(numbers[i],i));
        sort(store.begin(),store.end(),cmp());  
        vector<int> ans;  
        int n=numbers.size();  
        for(int p1=0,p2=n-1;p1<p2;){  
            int sum=store[p1].val+store[p2].val;  
            if(sum==target){  
                ans.push_back(min(store[p1].index,store[p2].index)+1);  
                ans.push_back(max(store[p1].index,store[p2].index)+1);  
                return ans;
            }  
            else if(sum < target)  
                p1++;  
            else p2--;  
        }  
        
        return ans;  
    }
};

answer2:

hash表存储对应的下标和个数

时间复杂度O(n),空间复杂度O(n)

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        unordered_map<int,int> mp;
        unordered_map<int,int> cnt;
        vector<int> result;
        for(int i=0;i<numbers.size();i++){
            mp[numbers[i]]=i;
            cnt[numbers[i]]++;
        }
            
        for(int i=0;i<numbers.size();i++){
            const int gap=target-numbers[i];
            if(mp.find(gap)!=mp.end()){
                if(gap==numbers[i]&&cnt[gap]==1)continue;
                
                result.push_back(i+1);
                result.push_back(mp[gap]+1);
                break;
            }
        }
        return result;
    }
};



你可能感兴趣的:(LeetCode)