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

  • 相关阅读:
    OOP & Pointer: Segment Tree
    ICPC_2020 上海站
    Notes: Kirchhoff's Matrix 基尔霍夫矩阵
    CS61A Homework: Church Numerals
    题解:[COCI2011-2012#5] BLOKOVI
    题解:SDOI2017 新生舞会
    题解:POI2012 Salaries
    题解:洛谷P1357 花园
    题解:CF593D Happy Tree Party
    题解 P2320 【[HNOI2006]鬼谷子的钱袋】
  • 原文地址:https://www.cnblogs.com/fanguangdexiaoyuer/p/9008532.html
Copyright © 2011-2022 走看看