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

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



LeetCode OJ:Two Sum

上一篇:oracle存储过程实例


下一篇:修改linux系统的root密码