zoukankan      html  css  js  c++  java
  • LeetCode OJ——Two Sum

    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;
    }
  • 相关阅读:
    转基因(转载)
    Diwali
    使用Matplotlib画图
    项目格式规范
    关于Dapper
    JQuery
    javascript封装
    2015年2月16日——作者观点
    2015年2月12日——不懂点
    在VS2013上使用git
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3389134.html
Copyright © 2011-2022 走看看