http://oj.leetcode.com/problems/two-sum/
求是否存在两个数的和为target,暴力法,两层循环
#include <iostream> #include <algorithm> #include <vector> using namespace std; class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { // Note: The Solution object is instantiated only once and is reused by each test case. //sort(numbers.begin(),numbers.end()); vector<int> answer; answer.clear(); if(numbers.size()<2) return answer; for(int index = 0;index<numbers.size()-1;index++) { for(int index2 = index+1;index2<numbers.size();index2++) { if(numbers[index2] == target - numbers[index]) { answer.push_back(index+1); answer.push_back(index2+1); return answer; } } } return answer; } }; int main() { Solution * mysolution = new Solution(); vector<int> numbers; numbers.push_back(150); numbers.push_back(24); numbers.push_back(79); numbers.push_back(50); numbers.push_back(88); numbers.push_back(345); numbers.push_back(3); vector<int> ans; int i = 0; ans= mysolution->twoSum(numbers,200 ); while(i!=ans.size()) { cout<<ans[i]<<" "; i++; } return 0; }