Leetcode 1.Two Sum

26 篇文章 1 订阅

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是STL的一個容器,它提供一對一的hash
        map<int,int>::iterator i;  //iterator-map容器的迭代器类型
        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:
复杂度O(N*N)
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums) - 1):
            for j in range(i + 1,len(nums)):
                if nums[i] + nums[j] == target:
                    return [i + 1,j + 1]
        return []
更高效的:

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




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值