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
  • 相关阅读:
    Add Two Numbers
    Same Tree
    Single Number
    题目1190:大整数排序
    题目1182:统计单词
    题目1181:遍历链表
    题目1180:对称矩阵
    题目1179:阶乘
    题目1206:字符串连接
    HTML事件
  • 原文地址:https://www.cnblogs.com/superzrx/p/3322297.html
Copyright © 2011-2022 走看看