LeetCode1--TwoSum

题目: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、第一次审题被误解,看到举例的Input,我以为给定的是有序数组,于是,写出下面的程序:

/**
*排序数组可以采取的方法:
*取头尾两个数字相加,比较结果和target数值,如果相等,则返回index位置,否则,由两头向中间递增或者递减。
*/
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> result;
        int begin = 0;
        int end = nums.size()-1;
        while(begin < end){
            if(nums[begin]+nums[end]==target){
                result.push_back(begin+1);
                result.push_back(end+1);
                return result;
            }else{
                nums[begin]+nums[end]>target?end--:begin++;
            }
        }
        return result;
    }
};

 

提交之后发现报错,提示信息:

Input:	[3,2,4], 6
Output:	[1,3]
Expected:	[2,3]

发现系统的测试用例Input是无序的,所以这种方法不可行。

 

2、重新做了一下,用map来存储中间生成的结果:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> result;
        map<int,int> store;
        for(int index=0;index<nums.size();index++){
            if(store.count(nums[index]) > 0){
                result.push_back(store[nums[index]]);
                result.push_back(index+1);
                return result;
            }else{
                store[target-nums[index]]=(index+1);
            }
        }
        return result;
    }
};

测试通过。

转载于:https://www.cnblogs.com/taxuegongzi/p/4572133.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值