2019-04-01

程序题1

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



answer

class Solution {

public:

    vector<int> twoSum(vector<int>& nums, int target)

    {

        vector<int>::iterator i,j;

        vector<int> a(2,0);

        for(i = nums.begin(); i<nums.end();++i)

        {

            for(j = i + 1; j<nums.end();++j)

            {

                if((*i + *j) == target)

                {

                    a[0] = i - nums.begin();

                    a[1] = j - nums.begin();

                    return a;

                }

            }

        }

        return a;

    }

};



这里使用了容器vector,和vector的迭代器,函数的返回值是一个vector<int>,所以这里需要建一个临时的vector<int>。通过遍历nums里面的元素,来找到两个加起来等于target的元素。而我们最后要返回的vector不是包含这两个元素的vector,而是包含这两个元素在nums里面的第几个,所以这里用到了迭代器与nums.begin()的距离。最后需要考虑到没有找到合适元素时,我们也需要返回一个vector<int>,所以在for循环外需要在return a。

总结:一开始忽略了没有遍历到答案的情况,导致一直报错:达到非空函数的底端(并不是所有分支都有返回值)。这是一个很容易疏忽的点,以后想问题应更加全面。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容