首页 > 学院 > 开发设计 > 正文

Two Sum

2019-11-06 07:59:27
字体:
来源:转载
供稿:网友

原题:

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

C++实现:

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


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表