LeetCode 1. Two Sum

来源:互联网 发布:如何在知乎发表文章 编辑:程序博客网 时间:2024/06/16 17:23



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


简而言之,就是给了一串数字,一个目标数,题目假设肯定存在一个答案,使‘一串数字’中的两个数字加起来等于目标数,并返回这两个数的下标。

下面是我的笨办法,用c++写的。

class Solution {public:       vector<int> twoSum(vector<int>& nums, int target) {        vector<int> ans;        vector<int>::iterator iter;        int n = nums.size();        int a[n],i,flag=0;        for(i=0,iter = nums.begin();iter!=nums.end();iter++,i++){            a[i]=*iter;        }        for(i = 0; i<n-1;i++){            for(int j =i+1;j<n;j++){                if(a[i]+a[j]==target){                    ans.push_back(i);                    ans.push_back(j);                    flag=1;                    break;                }            }            if(flag) break;        }        return ans;    }};