zoukankan      html  css  js  c++  java
  • LeetCode-1.Two Sum

    1.题目描述

    Given an array of integers, return indices of the two numbers such that they add up to a specific target.

    You may assume that each input would have exactly one solution, and you may not use the same element twice.

    Example:

    Given nums = [2, 7, 11, 15], target = 9,

    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].

    2.我的分析思路

    首先,最直接的思路就是遍历数组,分两次遍历,找到结果后直接返回即可。直接上代码:

    public static int[] twoSum(int[] nums, int target) throws IllegalArgumentException {
    	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 num found");
    }
    

    这个算法的时间复杂度为

    O(n^2)
    

    空间复杂度为:

    O(1)
    

    3.其他的思路

    3.1 思路1

    将所有数组内的下标和值存储到一个map中,然后只需要遍历一次数组,每个数据进行计算,算出对应的差值,如果这个差值在map中存在,那么就直接返回两个下标,否则抛出异常。

    public static 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");
    }
    

    分析这个算法,可以得到,这个算法的时间复杂度为:

    O(n)
    

    空间复杂度为:

    O(n)
    

    是典型的空间换时间的算法。

    思路2

    还是空间换时间的思路,直接遍历数组,计算差值,如果在map中存在这个值,直接返回,否则将数组中的值存入map中。

    public static int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement)) {
                return new int[] { map.get(complement), i };
            }
        map.put(nums[i], i);
        }
       throw new IllegalArgumentException("No two sum solution");
    }
    

    分析这个算法,可以得到,这个算法的时间复杂度为:

    O(n)
    

    空间复杂度为:

    O(n)
    

    是典型的空间换时间的算法。

  • 相关阅读:
    十,文献研读
    第十周博客作业
    【西北师大-2108Java】第八次作业成绩汇总
    【西北师大-2108Java】期中成绩汇总
    人脸识别性别的卷积神经网络
    主成分分析(PCA)原理详解
    使用KNN算法对鸢尾花数据集进行分类处理
    5.文献研读---基于教育数据挖掘的在线学习者 学业成绩预测建模研究--陈子健 朱晓亮
    4.文献研读---基于数据挖掘的学习者在线学习行为分析模型构建--卓荣庆 柏忠贤
    3.文献研读---基于Canvas Network开放数据集的MOOC学习分析--胡红梅 宗 阳
  • 原文地址:https://www.cnblogs.com/f-zhao/p/6369765.html
Copyright © 2011-2022 走看看