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

1. Two Sum

2019-11-06 08:21:17
字体:
来源:转载
供稿:网友

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

#include<algorithm>class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> re;//存储结果 vector<int> temp=nums;//存储原来的输出 int low=0,high=nums.size()-1; sort(nums.begin(),nums.end());//对原来输出进行排序 while(nums[low]+nums[high]!=target)//求那两个数的排序后位置 { if(nums[low]+nums[high]>target) high--; else low++; } low=nums[low];//求那两个数的值 high=nums[high]; for(int t=0;t<nums.size();t++)//通过值来求原来的位置 if(temp[t]==low || temp[t]==high) re.push_back(t); return re; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表