zoukankan      html  css  js  c++  java
  • 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

    代码

    暴力,时间复杂度为 O(N^2)

    public int[] twoSum(int[] numbers, int target) {
    int[] res = new int[2];
    for (int i = 0; i < numbers.length - 1; i++) {
      if (numbers[i] <= target) {
        for (int j = i + 1; j < numbers.length; j++) {
          if (target - numbers[i] == numbers[j]) {
            res[0] = i + 1;
            res[1] = j + 1;
          }
        }
      }
    }
    return res;
    }

    散列表hasmMap

    /**
    * 用 HashMap 存储数组元素和索引的映射,在访问到 nums[i] 时,判断 HashMap 中是否存在 target - nums[i]
    * 如果存在说明 target - nums[i] 所在的索引和 i 就是要找的两个数。
    * 该方法的时间复杂度为 O(N),空间复杂度为 O(N),使用空间来换取时间。
    * @param nums
    * @param target
    * @return
    */
    public int[] twoSum_2(int[] nums, int target) {
    HashMap<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
      if (map.containsKey(target - nums[i])) {
        return new int[] { map.get(target - nums[i]) + 1, i + 1 };
      } else {
        map.put(nums[i], i);
      }
    }
    return null;
    }

    先排序,首尾指针

    xx

  • 相关阅读:
    Double 四舍五入保留小数
    QQ在线人数统计图数据解析
    Errors running builder 'Android Resource Manager' on project 'DeskClock'.
    批处理脚本学习笔记——程序猿版
    BZOJ 1002: [FJOI2007]轮状病毒
    《逆袭大学——传给IT学子的正能量》文件夹
    webservice 开发规范
    webservice面试题
    jdbc连接oracle数据库问题
    jdbc连接 orale 和 mysql 所需要的jar包
  • 原文地址:https://www.cnblogs.com/fanguangdexiaoyuer/p/9008532.html
Copyright © 2011-2022 走看看