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
  • 相关阅读:
    (六)软件测试分工
    <C++>FILE和fstream
    <C#>序列化
    <C#>多线程
    <C++>面试
    <C#>面试
    <Linux>Linux系统命令
    <Linux>Linux基础知识
    <CAN>汽车诊断基础知识
    <C++>查询
  • 原文地址:https://www.cnblogs.com/superzrx/p/3322297.html
Copyright © 2011-2022 走看看