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

    题目描述:

    给定一个数组,一个数字(Target),寻找数组中两个数字a和b,使得a+b=Target,打印a和b的下标。

    题解:

    第一反应是如果直接遍历O(N^2)暴力求解肯定TLE,果不其然。

    第二反应是用二分查找,O(N*logN)的复杂度应该可以AC,但是我想到一个更简洁的方法,二分就没有测试。

    解决方法:

    使用HaspMap,遍历numbers数组,将target-numbers[i]放入map,对应的value是i,循环遍历,当发现当前数组元素已经存在于map中,说明和前面的某个元素加起来正好等于target;这时取出map中numbers[i]的value值+1作为第一个数的下标,数组下标i+1作为第二个数的下标。

    public int[] twoSum(int[] numbers, int target) {
            int[] res = new int[2];
            HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
            for (int i = 0; i < numbers.length; i++) {
                int key = numbers[i];
                if (map.containsKey(key)) {//如果map中存在,说明找到了
                    res[0] = map.get(key) + 1;
                    res[1] = i + 1;
                    break;
                } else {
                    map.put(target - key, i);//遍历numbers数组,将target-key放入map
                }
            }
            return res;
        }
  • 相关阅读:
    ICE-3.5.1-错误记录
    windows下qtcreator添加ICE库文件
    LINUX下QT与C语言通过网卡名获取网卡IP与MAC
    Apache部署Django+Vue
    三次握手和四次挥手面试常问
    配置mysql时报错
    nosql的介绍以及和关系型数据库的区别
    redis的基本操作
    在Centos安装redis-孙志奇
    git的使用
  • 原文地址:https://www.cnblogs.com/aboutblank/p/3690339.html
Copyright © 2011-2022 走看看