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

    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

    通过一个哈希表快速查询每个数对应的组成目标值的数是否存在

    构建hash表需要O(n)的时间复杂度

    class Solution {
    public:
        vector<int> twoSum(vector<int> &numbers, int target) {
            vector<int> ret;
            map<int,int> m;
            for(int i=0;i<numbers.size();i++){
                m[numbers[i]]=i;
            }
            for(int i=0;i<numbers.size();i++){
                if(m.find(target-numbers[i])!=m.end()){
                    int ind=m[target-numbers[i]];
                    if(ind!=i){
                        ret.push_back(i+1);
                        ret.push_back(m[target-numbers[i]]+1);
                        break;
                    }
                }
            }
            return ret;
        }
    };
    C++
    public class Solution {
        public int[] twoSum(int[] numbers, int target) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            HashMap<Integer,Integer> hashMap=new HashMap<Integer,Integer>();
            for(int i=0;i<numbers.length;i++){
                hashMap.put(numbers[i], i);
            }
            int ret[]=new int[2];
            for(int i=0;i<numbers.length;i++){
                if(hashMap.containsKey(target-numbers[i])){
                    if(hashMap.get(target-numbers[i])!=i){
                        ret[0]=i+1;
                        ret[1]=hashMap.get(target-numbers[i])+1;
                    }
                }
            }
            Arrays.sort(ret);
            return ret;
        }
    }
    Java
  • 相关阅读:
    Ch5 关联式容器(上)
    Ch4 序列式容器(下)
    Ch4 序列式容器(上)
    DNN模型学习笔记
    关于换博客的说明
    睡前一小时数学之导数的学习与证明
    OpenJudge 666:放苹果 // 瞎基本DP
    OpenJudge 2990:符号三角形 解析报告
    OpenJudge1700:八皇后问题 //不属于基本法的基本玩意
    BZOJ1088扫雷Mine 解析报告
  • 原文地址:https://www.cnblogs.com/superzrx/p/3322297.html
Copyright © 2011-2022 走看看