【leetCode】Two Sum

来源:互联网 发布:网络兼职招聘 编辑:程序博客网 时间:2024/05/24 05:17

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

大意:

给一个整形数组nums[],从中找出两个数A、B,使得A+B等于给定值K。

函数要求返回这两个数的下标(从1开始计数),并且前面那个下标要比后面那个大才行。

思路:

那个本来两个for循环的暴力手法是行不通的。但是大家发现leetCode对时间的要求并没有那么严格,于是第二个for循环改成二分查找也能通过.....

多多少少有些钻空子的意思。

无独有偶,在阿里面试的时候面试官也问了我这个问题。当时没答上,现在把我的做法写出来算是弥补下这个遗憾。

我的思路很常规:

1、用一个multimap存放数组中所有元素的<值,下标>。用multimap的原因是数组中的值可能重复出现。这里我们先管这个multmap就叫map好了。

2、遍历数组,对一个值 nums[i],计算 k-nums[i]。然后在map中去查找 k-nums[i]。

2.1、如果没有找到k-nums[i],就 i++ ;

2.2、如果找到了,就检查 k-nums[i]== nums[i]的真假;

2.2.1、如果k-nums[i]== nums[i],且 nums中只有一个元素的值 == num[i](比如{3,2,4},然后K==6,这种情况 "3"就要舍去)。直接i++到下一次循环;

2.2.2、如果k-nums[i]== nums[i],且 nums中有两个元素的值 == num[i](比如{3,3,2,5},k == 6。这种情况就要保留3)。直接进入到步骤2.3;

2.3、通过map查找到所有值为 k-nums[i]的元素(返回的是个迭代器),递增这个迭代器,将这些元素连同之前的nums[i]一起压入保存结果的vector。

好了,翠花,上代码:

class Solution {public:vector<int> twoSum(vector<int>& nums, int target) {//保存结果//keep the resultvector<int> r;//第一个int:nums[index]//第二个int: indexmultimap<int, int> map;//put all elements in nums into map//把nums中的元素丢进map中去for (int i = 0; i < nums.size(); i++){map.insert(make_pair(nums[i], i));}int firstNum = 0;//index1int lastNum = 0;//index2for (int i = 0; i < nums.size(); i++){//取得第一个数firstNum = nums[i];//算出还需要一个多大的数lastNumlastNum = target - firstNum;//在map中寻找有多少个元素的值等于lastNum的数int count = map.count(lastNum);//没找到就将nums中下一个数设为firstNumif (count == 0)continue;//否则对这个lastNum的位置进行考察else{//检查一下这个lastNum所在的index是不是firstNum所在的index//发现lastNum==firstNum,且nums只有一个lastNum/firstNum,就放弃这个数if (map.count(firstNum) == 1 && firstNum == lastNum)continue;auto searchResult = map.find(lastNum);while (count){if (searchResult->second != i){r.push_back(i + 1);r.push_back(searchResult->second + 1);}--count;++searchResult;}break;}}std::sort(r.begin(), r.end(), less<int>());return r;}};

运行结果:




0 0
原创粉丝点击