Loading

【leetcode】1. Two Sum

  Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.

  

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        //暴力法的时间复杂度是o(n2),显然很蠢
        //用hash_Set 就像那个递归的 hash_set 存储坐标
        // 利用vector 迭代器的性质做
        vector<int> res;
        bool flag=false;
        vector<int>::iterator it;
        vector<int>::iterator tmp;
        for(it=nums.begin();it!=nums.end();it++)
        {
            int num=target-*it;
            tmp=find(it+1,nums.end(),num);
            if(tmp!=nums.end())
            {
                flag=true;
                break;
            }
        }
        if(flag)
        {
            res.push_back((int)distance(nums.begin(),it));
            res.push_back((int)distance(nums.begin(),tmp));
        }
        

        return res;
        
        
    }
};

 

posted @ 2021-11-19 21:26  aalanwyr  阅读(21)  评论(0编辑  收藏  举报