Leetcode 1.Two Sum

来源:互联网 发布:vb.net 添加控件 编辑:程序博客网 时间:2024/06/11 15:57

Leetcode 1.Two Sum

Problem:

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 thetarget, 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

 

C++:

(遍历)

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        for(int i = 0; i < nums.size(); ++i){          for(int j = i + 1; j < nums.size(); ++j){              if(nums[i] + nums[j] == target){                  vector<int> v_Ints;    //创建空的vector对象                  v_Ints.push_back(i);  //依次把整数值放到v_Ints尾端                  v_Ints.push_back(j);  //两层循环构建矩阵                  return v_Ints;              }          }           }    }};
 (哈希算法)
#include<iostream>#include<vector>#include<map>#include<math.h>#include<algorithm>using namespace std;class Solution {public:    vector<int> twoSum(vector<int> &numbers, int target) {        vector<int> result;        map<int,int> nummap;        map<int,int>::iterator i;        for(int i = 0 ;i < numbers.size(); i++)                nummap.insert(make_pair(numbers[i],i+1));//map中key存放numbers数组的值,value存放下标        for(map<int ,int >::iterator iter = nummap.begin(); iter!= nummap.end(); iter++)        {                int value1 = iter->first;                int value2 = target - value1;                i = nummap.find(value2);                if( i != nummap.end())                {                    if(value1 + value2 == target)                    {                        if(value1 == value2)//看找到的值是否为target的二分之一,若是二分之一,必须存在2个才符合要求                        {                            vector<int>::iterator j;                            vector<int>::iterator k = find (numbers.begin(), numbers.end(), value1);                            if(k!= numbers.end())//看是否存在两个                            {                                j = find(k+1, numbers.end(), value1);                                if(j!= numbers.end())                                {                                    result.push_back(k-numbers.begin()+1);                                    result.push_back(j-numbers.begin()+1);                                    return result;                                }                            }                        }                        else//若不是二分之一,说明存在两个不同下标的不同值相加为target,从map中取出他们相应的索引                        {                                result.push_back(min(nummap[value1],nummap[value2]));                                                        result.push_back(max(nummap[value1],nummap[value2]));                             return result;                        }                    }                }        }        return result;    }};int main (){    Solution s1;    int num[] ={0, 2, 4, 0};    vector<int> numbers (num,num+4);    int target = 0;    vector<int> result = s1.twoSum(numbers, target);    for(int i = 0 ;i < result.size(); i++)    {        cout<< result[i]<<endl;    }    return 0;}
Python:
class Solution(object):  def twoSum(self, nums, target):  """  :type nums: List[int]  :type target: int  :rtype: List[int]  """  d = {}   #创建一个字典  for i in range(0,len(nums)):   #数组范围大小     if nums[i] in d:           #如果数组内的数在字典内,输出字典key对应的value         return [d[nums[i]]-1, i]     else:                              #如果不在字典内,目标值减去数组中的值当作key存入字典,并给定对应value        d[target - nums[i]] = i + 1

 

参考:

http://blog.csdn.net/katherineleeyq/article/details/51165602

https://www.cnblogs.com/louyihang-loves-baiyan/p/4455638.html

http://www.jianshu.com/p/258749016d05




原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 电脑屏膜变大了怎么办 手机2g模块坏了怎么办 腾讯大王卡是2g怎么办 华为手机4g坏了怎么办 优盘中毒打不开怎么办 vr头戴链接不起怎么办 人在缺氧的时候怎么办 脑缺氧供血不足怎么办 睡多了大脑缺氧怎么办 吃了过期的东西怎么办 吃了过期的牛肉怎么办 生存战争肉腐烂了怎么办? 家里进了蝙蝠找不到了怎么办 方舟手游恐龙找不到了怎么办 这是我的战争怎么办 小孩吃坏东西呕吐发烧怎么办 睿芽密码忘了怎么办 做绿豆糕太稀了怎么办 自热火锅吃完后怎么办 自煮火锅吃完了怎么办 自热火锅没熟怎么办 厕所被米饭堵了怎么办 减完肥肉特别松怎么办 新开的熟食店没人光顾怎么办 吃剩的软炸里脊怎么办 小火锅加热时胀盒该怎么办 天丝面料容易皱怎么办 快递员拒不送件怎么办 鞋店里面买到假鞋子了怎么办 孕吐伤了胃疼怎么办 孕期吐的胃疼怎么办 买的巧克力化了怎么办 跑步后脸上出盐怎么办 头发被剪的很短怎么办 孩子做事情拖拉不专注怎么办 新热水壶有味道怎么办 新买电热壶有味怎么办 两个月狗耳朵臭怎么办 狗狗牙齿变黄怎么办 人用了狗沐浴露怎么办 狗狗吞食牙膏吐怎么办?