麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

LeetCode-1.Two Sum

2019-11-11 05:28:04
字體:
供稿:網(wǎng)友

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.我的分析思路

首先,最直接的思路就是遍歷數(shù)組,分兩次遍歷,找到結(jié)果后直接返回即可。直接上代碼:

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

這個(gè)算法的時(shí)間復(fù)雜度為

O(n^2)

空間復(fù)雜度為:

O(1)

3.其他的思路

3.1 思路1

將所有數(shù)組內(nèi)的下標(biāo)和值存儲(chǔ)到一個(gè)map中,然后只需要遍歷一次數(shù)組,每個(gè)數(shù)據(jù)進(jìn)行計(jì)算,算出對應(yīng)的差值,如果這個(gè)差值在map中存在,那么就直接返回兩個(gè)下標(biāo),否則拋出異常。

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

分析這個(gè)算法,可以得到,這個(gè)算法的時(shí)間復(fù)雜度為:

O(n)

空間復(fù)雜度為:

O(n)

是典型的空間換時(shí)間的算法。

思路2

還是空間換時(shí)間的思路,直接遍歷數(shù)組,計(jì)算差值,如果在map中存在這個(gè)值,直接返回,否則將數(shù)組中的值存入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");}

分析這個(gè)算法,可以得到,這個(gè)算法的時(shí)間復(fù)雜度為:

O(n)

空間復(fù)雜度為:

O(n)

是典型的空間換時(shí)間的算法。


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 日韩黄色精品视频 | 成人毛片免费视频 | 在线日韩亚洲 | 国产一级aaa全黄毛片 | 91网站在线观看视频 | 一级免费特黄视频 | 最新在线黄色网址 | 欧美aaaaaaaa | 深夜免费福利视频 | 在线播放污 | 激情视频免费看 | 成人在线视频在线观看 | 日本不卡二区 | av在线免费网址 | 双性精h调教灌尿打屁股的文案 | 欧美片一区二区 | 成人免费视频 | 操操日日| 国产精品亚洲欧美一级在线 | 亚洲国产精品久久久久婷婷老年 | 91av网址| 欧美日韩中文字幕在线视频 | 久久久久久久一区 | 日韩欧美电影在线观看 | 91久久在线观看 | 国产欧美一区二区三区免费看 | 天天夜夜草 | 亚洲午夜在线视频 | 91av资源在线 | 国产亚洲精品视频中文字幕 | 依人在线视频 | 毛片国产 | 91成人在线免费观看 | 综合网日日天干夜夜久久 | 第一区免费在线观看 | 免看黄大片aa | 欧美成人三级视频 | 成人国产视频在线观看 | 欧美一区在线观看视频 | 久久艹一区| 午夜国内精品a一区二区桃色 |