【LeetCode】1. Two Sum

来源:互联网 发布:海绵城市规划模型软件 编辑:程序博客网 时间:2024/05/17 22:56

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

【解题思路】

【代码】

class Solution {    public:        vector<int> twoSum(vector<int>& nums, int target) {        vector<int> ans;            for(int i = 0;i < nums.size();i++) {                vector<int>::iterator ite = find(nums.begin() + i + 1, nums.end(), target - nums[i]);                if(ite != nums.end()) {                    ans.push_back(i);                    ans.push_back(ite - nums.begin());                    return ans;                }            }        }    };
0 0