第一週LeetCode算法題之一

題目名稱:Two Sum

題目難度:Easy

題目描述: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.

例子:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].



題目分析:
非常基礎的一道算法題,看完題目之後的第一思路就是寫個雙重循環直接遍歷整個數組找出答案即可。
考察的知識點除了算法思路還有vector容器的應用。
訪問vector容器中的元素的方法有兩個:
1、直接用[index]下標進行訪問。
2、使用迭代器進行訪問:

for(vector<int>::iterator it=b.begin();it!=b.end();it++) {
    ...
}



最後的解題代碼如下:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        for (int i = 0; i < nums.size(); ++i) {
          for (int j = i + 1; j < nums.size(); j++) {
            if ((nums[i] + nums[j]) == target) {
              vector<int> result;
              result.push_back(i);
              result.push_back(j);
              return result;
            }
          }
        }
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章