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;
            
            
            
        }
    };
  • 相关阅读:
    call、apply、bind函数的理解以及手写。
    父div里两个子div(inline-block),为什么两个子div中间会有小缝隙,如何解决?
    手写柯里化
    arguments的理解
    New
    BFC
    useCallBack和useMemo的用法
    观察者模式和发布订阅模式
    grid布局
    Android常见输入法的包名和主类名
  • 原文地址:https://www.cnblogs.com/obama/p/3266680.html
Copyright © 2011-2022 走看看