【LeetCode C++】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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解题:


题目的意思是给定一个一维的数组nums和一个目标值target,查找数组中是否存在两个整数元素的和为目标值target。返回符合条件的整数元素在一维数组中的位置。

遍历法:

时间复杂度:O(n2)  Runtime: 760 ms

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

运行结果:

遍历法是最耗时的算法,因此需要进一步优化算法。

posted on 2016-04-25 15:42  看云  阅读(221)  评论(0编辑  收藏  举报

导航

http://home.cnblogs.com/group/topic/8550.html