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;
        }
  • 相关阅读:
    python 语法
    python调试
    08 ES6 基本介绍
    微信小程序中 一些封装的函数
    07 豆瓣小程序项目
    06自定义组件 和 网络请求api
    05 常用组件 和 小程序WXS语法
    04小程序逻辑层App() ,Page() 中的生命周期函数 和 页面路由(页面栈 )
    03小程序的WXSS 和 flex 布局
    02小程序的WXML 和 事件
  • 原文地址:https://www.cnblogs.com/aboutblank/p/3690339.html
Copyright © 2011-2022 走看看