leetcode---TwoSum

来源:互联网 发布:穿越小说改编的网络剧 编辑:程序博客网 时间:2024/06/05 15:51

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, and you may not use the same element twice.

Example:

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


class Solution {    vector<int> result;public:    vector<int> twoSum(vector<int>& nums, int target) {        if(nums.size()<2) return result;       // int length=nums.size();       // sort(nums.begin(),nums.end());       // auto index=find_if(nums.begin(),nums.end(),[target](int &data){return target<=data;});        for(auto beg1=nums.begin();beg1!=nums.end()-1;beg1++){            for(auto beg2=beg1+1;beg2!=nums.end();beg2++){                if(*beg1+*beg2==target){                    result.push_back(beg1-nums.begin());                    result.push_back(beg2-nums.begin());                    break;                }             }           // if(result.size()>0) break;        }        return result;    }    };


for(auto beg=nums.begin();beg!=nums.end()-1;beg++){            int anothernum=target-*beg;            auto f=find(nums.begin()+(beg-nums.begin())+1,nums.end(),anothernum);            if(f!=nums.end()){                result.push_back(beg-nums.begin());                result.push_back(f-nums.begin());                break;            }        }


原创粉丝点击