zoukankan      html  css  js  c++  java
  • leetcode--Two Sum

    1.题目描述

    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.解法分析

    由于题目说得很明白,一定有解且解只有一组,那么这题用hash做自然是最快了,但是对于偶数输入,比如target为8,如果结果是4和4的相加需要特殊考虑。

    class Solution {
    public:
        vector<int> twoSum(vector<int> &numbers, int target) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            unordered_set<int> myHash;
            vector<int>::iterator iter;
            vector<int> result;
            result.assign(2,0);
            
            if(target%2==0)
            {
                int count=0;
                for(int i=0;i<numbers.size();++i)
                {
                    if(numbers[i]==target/2)
                    {
                        if(count==0){result[0]=i+1;count++;}
                        else {result[1]=i+1;return result;}
                    }
                }
            }
            
            for(iter=numbers.begin();iter!=numbers.end();++iter)
            {
                myHash.insert(*iter);
            }
            
     
            
            for(int i=0;i<numbers.size();++i)
            {
                myHash.erase(numbers[i]);
                if(myHash.count(target-numbers[i])==1)
                {
                    result[0]=i+1;break;
                }
                myHash.insert(numbers[i]);
            }
            
            for(int i=result[0];i<numbers.size();++i)
            {
                if((numbers[result[0]-1]+numbers[i])==target)
                {
                    result[1]=i+1;break;
                }
            }
            
            return result;
            
            
            
        }
    };
  • 相关阅读:
    手撕RPC框架
    关于JVM的一些冷知识
    luoguP2627 修剪草坪
    [USACO16OPEN]248
    luoguP1171 售货员的难题
    luoguP2016 战略游戏
    luoguP2422 良好的感觉
    POJ1160 [IOI2000]Post Office
    luoguP2015 二叉苹果树
    BZOJ1756 小白逛公园
  • 原文地址:https://www.cnblogs.com/obama/p/3266680.html
Copyright © 2011-2022 走看看