[LeetCode]--Tow Sum

来源:互联网 发布:魔兽世界数据库 编辑:程序博客网 时间:2024/05/21 11:31

题目:

   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++这种编程语言,LeetCode的解题框中已经给出算法的整体框架,利用向量<vector>的基本数据类型及有关基本操作,便可以得到题目的正解。

 

解答:

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        vector<int> result;        for(int i=0;i<(nums.size()-1);i++){            for(int j=i+1;j<nums.size();j++){                if(nums[i]+nums[j]==target){                    result.push_back(i);                    result.push_back(j);                    break;                }            }        }        return result;    }};
        其中,push_back为vector容器的尾部插入操作,这里可以理解为向数组中添加新的元素。size()函数返回vector容器中实际数据的个数。采用嵌套循环,当数组中两数之和等于target的值时,向result容器中分别插入这两数的下标,根据题目要求,每个数组中只能找到唯一的满足要求的组合,因此一旦找到便停止循环,降低了算法的复杂度。
   这个解法的时间复杂度为O(n^2),空间复杂度为O(n)。
      我们也可以考虑增加判断条件,例如,当某数比target的值大时,即跳至下一个数,会更加减化算法。