zoukankan      html  css  js  c++  java
  • 快速寻找满足条件的两个数

    《编程之美》里的一个题目:能否快速找出一个数组中的两个数字,让这两个数字之和等于一个给定的值,假设这个数组中肯定存在至少一组符合要求的解。

    LeetCode的题目:

    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

    Leetcode的要求要返回索引,比编程之美的要难一些,leetcode论坛里讨论的是用hashmap来做的,实际应用中是可以的,面试时用hashmap就不一定被面试官允许了,如果不允许怎么办呢?

    一个办法是复制原来的数组,并对其排序,排序后的数组有额外一个值保存其原来数组的索引,然后再用变成有序数组,就好做了,不过这样需要O(n)的内存空间,但Hashmap也是O(n)的内存空间,计算效率最小为nlgn,比用hashmap稍逊一筹。

  • 相关阅读:
    XMIND
    android studio 更新 Gradle错误解决方法
    解决下载Android Build-tools 19.1.0失败
    Android Studio怎么删除项目
    android studio 更改背景和设置字体大小
    IOS开发常用技术网站
    Gitbook安装
    深入解析AsyncTask(转)
    Android中Bitmap和Drawable(转)
    提高Android在eclipse下的编译速度
  • 原文地址:https://www.cnblogs.com/whyandinside/p/3926966.html
Copyright © 2011-2022 走看看