1. 程式人生 > 其它 >【leetcode】1. Two Sum

【leetcode】1. Two Sum

  Given an array of integersnumsand an integertarget, returnindices of the two numbers such that they add up totarget.You may assume that each input would haveexactlyone solution, and you may not use thesameelement 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; } };