刷LeetCode(1)——两数相加

来源:互联网 发布:linux系统下删除用户 编辑:程序博客网 时间:2024/06/05 13:35

刷LeetCode(1)——两数相加

Code it now! https://leetcode.com/problems/two-sum/
难度:简单 频率:高

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].

题目比较简单,直接通过暴力方法来进行求解。

#include <vector>#include <iostream>#include <algorithm>using namespace std;class Solution {public:    static vector<int> twoSum(vector<int>& nums, int target) {        vector<int> v(2,0);        const int len = nums.size();        for( int i=0;i<len;++i)        {            for( int j=i+1;j<len;++j)            {                if( nums[i] + nums[j] == target )                {                    v[0] = i;                    v[1] = j;                    return v;                }            }        }        return v;    }};int main(){    vector<int> result;    vector<int> vec(3,0);    vec[0] = 3;    vec[1] = 2;    vec[2] = 4;    result = Solution::twoSum(vec,6);    for( vector<int>::iterator iter=result.begin(); iter != result.end(); ++iter)    {        cout << " " << (*iter);    }    cout << endl;}

大家如果有好的办法可以一起讨论讨论。

原创粉丝点击