• 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

  • 相关阅读:
    thinkphp5整合 gatewaywork实现聊天
    php输出日志
    php的ob函数实现页面静态化
    30个php操作redis常用方法代码例子
    redis三种启动方式
    Redis实战
    支付宝即时到账接口开发
    PHP生成excel表格文件并下载
    微信平台提供三种公众号
    【Performance】chrome调试面板
  • 原文地址:https://www.cnblogs.com/fanguangdexiaoyuer/p/9008532.html
Copyright © 2020-2023  润新知