leetcode习题笔记

从基础题目入手,按类别,写每个题,记录疑问与收获。

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

代码:

class Solution {
public:
  vector<int> twoSum(vector<int>& nums, int target) {
    int i,j;
    vector<int> indices;
    for (i=0;i<nums.size()-1;++i)
    {
      for (j=i+1;j<nums.size();++j)
      {
        if (i!=j)
        {
          if (nums[i]+nums[j]==target)
          {
            indices.push_back(i);
            indices.push_back(j);
            return indices;
          }
        }
      }
    }
  }
};

第一遍刷,先通过,对速度暂时不要求。算法知识边学习,边补充。

posted @ 2017-12-01 21:18  The_Silencer  阅读(177)  评论(0)    收藏  举报