zoukankan      html  css  js  c++  java
  • 算法天天练2:根据和值找到数组元素下标

    题目来源: https://leetcode.com/problems/two-sum/
    问题描述: 从数组中取出任意两个元素计算和值,根据和值反推元素下标。
    举例说明:

    define nums = [2, 7, 11, 15], target = 9
    Because nums[0] + nums[1] = 2 + 7 = 9
    return [0, 1]
    
    示例数组 示例和值 返回结果 解释
    [2, 7, 11, 15] 9 [0,1] 2 + 7 = 9
    [2, 3, 10, 15] 12 [0,3] 2 + 10 = 12

    解决方案

    1. 双重遍历逐一匹配,时间复杂度Ο(n^2)
    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[j] == target - nums[i]) {
                    return new int[] { i, j };
                }
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }
    

    2.采用map预装其中一个数,虽然时间复杂度是Ο(n),map的集合操作也是耗时的

    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement) && map.get(complement) != i) {
                return new int[] { i, map.get(complement) };
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }
    
  • 相关阅读:
    PyQt 滚动条自动到最底部
    Python 装饰器示例,计算函数或方法执行时间
    pyuic5将.ui文件转为.py文件
    Python pyinstaller 参数
    Win+R 常用命令
    CODEVS 2171 棋盘覆盖
    P3924 康娜的线段树
    P1850 换教室
    U33405 纽约
    POJ
  • 原文地址:https://www.cnblogs.com/xiaoyangjia/p/11650903.html
Copyright © 2011-2022 走看看