• 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

  • 相关阅读:
    java 整型相除得到浮点型
    Interleaving String
    Insert Interval
    Mashup
    R-TREE
    默认以管理员身份运行VS2013/15/17
    C:malloc/calloc/realloc/alloca内存分配函数
    VS2015快捷键
    C++:UNREFERENCED_PARAMETER用法
    VC++常用数据类型及其操作详解
  • 原文地址:https://www.cnblogs.com/fanguangdexiaoyuer/p/9008532.html
Copyright © 2020-2023  润新知