leetcode 1:Two Sums

来源:互联网 发布:斯里兰卡猛虎组织 知乎 编辑:程序博客网 时间:2024/06/05 15:19

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

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

Example:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

ACC:beats 98.34% cpp accpetors...

class Solution {public:    static bool cmp(pair<int,int> x,pair<int,int> y){        return x.first<y.first;    }    vector<int> twoSum(vector<int>& nums, int target) {        pair<int,int> p[nums.size()];        for(int k=0;k<nums.size();k++){            p[k].first=nums[k];            p[k].second=k;        }        sort(p,p+nums.size(),cmp);        int i=0,j=nums.size()-1;        vector<int> vec;        while(i<j){            if(p[i].first+p[j].first==target)            {                vec.push_back(p[i].second);                vec.push_back(p[j].second);                i++;                j--;            }            else if(p[i].first+p[j].first<target){                i++;            }            else{                j--;            }        }        return vec;    }};

0 0