Two Sum

来源:互联网 发布:mac 当前用户路径 编辑:程序博客网 时间:2024/05/10 10:32

问题描述

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

给定一个整型数组,找到数组内的两个数使得两者之和等于给定的target值,返回定义的下标。假设每个输入都有唯一的输出结果。

解决方案

直接遍历数组,直到找到结果。(我采用的方案,毕竟第一题,所以没想太多)

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