国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

LeetCode-1.Two Sum

2019-11-11 06:05:47
字體:
來源:轉載
供稿:網友

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)

是典型的空間換時間的算法。


上一篇:文件讀寫注意事項

下一篇:LA 3135 Argus

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 故城县| 门头沟区| 萨嘎县| 平邑县| 无棣县| 富阳市| 上林县| 天津市| 林西县| 新营市| 宽甸| 凤台县| 栖霞市| 顺昌县| 南昌县| 成安县| 金川县| 崇义县| 易门县| 湘潭县| 邳州市| 玉溪市| 静海县| 福贡县| 分宜县| 荆门市| 黔西县| 手游| 皮山县| 石景山区| 奉新县| 万安县| 嵩明县| 修文县| 涟源市| 浦东新区| 巢湖市| 镇坪县| 库伦旗| 太谷县| 马公市|