LeetCode - 1. Two Sum

来源:互联网 发布:windows欢迎界面 编辑:程序博客网 时间:2024/05/22 05:08

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.

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

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

题意

输入为一个数组和一个targe数字,要求返回数组中两个数的和为target的数的下标数组。你可以假设每个输入只有一个结果。

思路

这道题就太简单了,就是求两个数的和为target的数的下标。直接查询就可以了。但是需要注意:题目提示只有一个结果。说明找到一组解就可以 break!,不需要找出所有的解。

代码

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        vector<int> iList;        for (int i = 0; i < nums.size(); ++i){            for (int j = i + 1; j < nums.size(); ++j){                if (nums[i]+nums[j]==target){                    iList.push_back(nums[i]);                    iList.push_back(nums[j]);                    break;                }            }        }        return iList;    }};
0 0
原创粉丝点击