码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode.001 Two Sum

时间:2015-07-17 00:06:27      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

题意

从一个数组中找到两个数,使这两个数之和等于给定的目标数。   返回这两个数在数组中的位置

思路

1.将原数组复制在temp中,并排序

2.从排序数组的头和尾开始扫描:如果head+tail<target,那么head++,接着扫描;

   如果head+tail>target,那么tail--,接着扫描;直到head+tail=target。

3.从原数组中找到temp[head] 和 temp[tail]。

 1 //Runtime: 16 ms
 2 class Solution {
 3 public:
 4     vector<int> twoSum(vector<int>& nums, int target) {
 5     vector<int> temp = nums;
 6     sort(temp.begin(),temp.end());
 7     int head = 0;
 8     int tail = temp.size()-1;
 9     while(temp[head]+temp[tail] != target)
10     {
11         if(temp[head]+temp[tail] > target)
12             tail--;
13         else
14             head++;
15     }
16     vector<int> array(2,0);
17     for(int i=0;i<temp.size();i++)
18     {
19         if(nums[i] == temp[head] || nums[i] == temp[tail])
20             if(array[0] == 0)
21                 array[0] = i+1;
22             else
23                 array[1] = i+1;
24     }
25     return array;
26     }
27 };

 

LeetCode.001 Two Sum

标签:

原文地址:http://www.cnblogs.com/madking/p/4652685.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!